OpenCL: 解决图像半透明算法

来源:互联网 发布:alien skin mac 编辑:程序博客网 时间:2024/06/03 16:57

http://www.cocoachina.com/bbs/read.php?tid=33105&keyword=opencl

以下代码就是本人针对之前的OpenCL教程,结合各位能掌握的程度列出的一个示例代码。这份代码由本人亲手炮制。 先贴代码,然后讲解。这里再附上完整的工程。这份代码,当然仍然只能在Snow Leopard下才能运行,因为Leopard上没有OpenCL驱动。

[cpp] view plaincopy
  1. /*  
  2.  *  hello.c  
  3.  *  OpenCL_init  
  4.  *  
  5.  *  Created by Zenny Chen on 9/1/10.  
  6.  *  Copyright 2010 GreenGames Studio. All rights reserved.  
  7.  *  
  8.  */   
  9.   
  10.   
  11. #include <fcntl.h>   
  12. #include <stdio.h>   
  13. #include <stdlib.h>   
  14. #include <string.h>   
  15. #include <math.h>   
  16. #include <unistd.h>   
  17. #include <sys/types.h>   
  18. #include <sys/stat.h>   
  19. #include <OpenCL/opencl.h>   
  20.   
  21. ////////////////////////////////////////////////////////////////////////////////   
  22. // Use a static data size for simplicity   
  23. //   
  24. #define IMAGE_X_PIXELS          176   
  25. #define IMAGE_Y_PIXELS          144   
  26. #define IMAGE_SOURCE1_LIMPID    0.5f   
  27. #define IMAGE_SOURCE2_LIMPID    0.5f   
  28.   
  29. ////////////////////////////////////////////////////////////////////////////////   
  30.   
  31. // Simple compute kernel which computes the square of an input array    
  32. //   
  33. const char *KernelSource = "\n" \   
  34. "#define IMAGE_Y_PIXELS   144                                           \n" \   
  35. "#define IMAGE_SOURCE1_LIMPID   0.5f                                    \n" \   
  36. "#define IMAGE_SOURCE2_LIMPID   0.5f                                    \n" \   
  37. "                                                                       \n" \   
  38. "__kernel void Limpid(                                                  \n" \   
  39. "   __global float image1[][IMAGE_Y_PIXELS],                            \n" \   
  40. "   __global float image2[][IMAGE_Y_PIXELS],                            \n" \   
  41. "   __global float output[][IMAGE_Y_PIXELS])                            \n" \   
  42. "{                                                                      \n" \   
  43. "   int x = get_global_id(0);                                           \n" \   
  44. "   int y = get_global_id(1);                                           \n" \   
  45. "   output[x][y] = image1[x][y] * IMAGE_SOURCE1_LIMPID + image2[x][y] * IMAGE_SOURCE2_LIMPID; \n" \   
  46. "}                                                                      \n" \   
  47. "\n";   
  48.   
  49.   
  50. ////////////////////////////////////////////////////////////////////////////////   
  51.   
  52.   
  53. int main(int argc, char** argv)   
  54. {   
  55.     int err;                            // error code returned from api calls   
  56.   
  57. float *image1, *image2;             // original data set given to device   
  58.     float *results;                     // results returned from device   
  59. unsigned int correct;               // number of correct results returned   
  60.   
  61. size_t global;                      // global domain size for our calculation   
  62. size_t local;                       // local domain size for our calculation   
  63.   
  64.     cl_platform_id  platform_id;        // added by zenny_chen   
  65.     cl_device_id device_id;             // compute device id    
  66.     cl_context context;                 // compute context   
  67.     cl_command_queue commands;          // compute command queue   
  68.     cl_program program;                 // compute program   
  69.     cl_kernel kernel;                   // compute kernel   
  70.   
  71. cl_mem input1, input2;              // device memory used for the input array   
  72. cl_mem output;                      // device memory used for the output array   
  73.   
  74.   
  75.   
  76. // Initialize the original data buffer and the result buffer   
  77.     image1 = (float*)malloc(IMAGE_X_PIXELS * IMAGE_Y_PIXELS * sizeof(*image1));   
  78.     image2 = (float*)malloc(IMAGE_X_PIXELS * IMAGE_Y_PIXELS * sizeof(*image2));   
  79.     results = (float*)malloc(IMAGE_X_PIXELS * IMAGE_Y_PIXELS * sizeof(*results));   
  80. const unsigned int count = IMAGE_X_PIXELS * IMAGE_Y_PIXELS;   
  81.   
  82. // Automatically generate 2 images   
  83.     for(int i = 0; i < count; i++) {   
  84.         image1[i] = rand() / (float)RAND_MAX;   
  85.         image2[i] = rand() / (float)RAND_MAX;   
  86.     }   
  87.   
  88. // Create a platform   
  89.     err = clGetPlatformIDs(1, &platform_id, NULL);   
  90.     if (err != CL_SUCCESS)   
  91.     {   
  92. printf("Error: Failed to create a platform!\n");   
  93. return EXIT_FAILURE;   
  94.     }   
  95.   
  96. // Connect to a compute device   
  97.     //   
  98.     err = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, 1, &device_id, NULL);   
  99.     if (err != CL_SUCCESS)   
  100.     {   
  101. printf("Error: Failed to create a device group!\n");   
  102. return EXIT_FAILURE;   
  103.     }   
  104.   
  105. // Create a compute context    
  106.     //   
  107.     context = clCreateContext((cl_context_properties[]){(cl_context_properties)CL_CONTEXT_PLATFORM, (cl_context_properties)platform_id, 0}, 1, &device_id, NULL, NULL, &err);   
  108.     if (!context)   
  109.     {   
  110. printf("Error: Failed to create a compute context!\n");   
  111. return EXIT_FAILURE;   
  112.     }   
  113.   
  114. // Create a command commands   
  115.     //   
  116.     commands = clCreateCommandQueue(context, device_id, 0, &err);   
  117.     if (!commands)   
  118.     {   
  119. printf("Error: Failed to create a command commands!\n");   
  120. return EXIT_FAILURE;   
  121.     }   
  122.   
  123. // Create the compute program from the source buffer   
  124.     //   
  125.     program = clCreateProgramWithSource(context, 1, (const char **) & KernelSource, NULL, &err);   
  126.     if (!program)   
  127.     {   
  128. printf("Error: Failed to create compute program!\n");   
  129. return EXIT_FAILURE;   
  130.     }   
  131.   
  132. // Build the program executable   
  133.     //   
  134.     err = clBuildProgram(program, 0, NULL, NULL, NULL, NULL);   
  135.     if (err != CL_SUCCESS)   
  136.     {   
  137.         size_t len;   
  138.         char buffer[2048];   
  139.   
  140. printf("Error: Failed to build program executable!\n");   
  141.         clGetProgramBuildInfo(program, device_id, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &len);   
  142.         printf("%s\n", buffer);   
  143.         exit(1);   
  144.     }   
  145.   
  146. // Create the compute kernel in the program we wish to run   
  147.     //   
  148.     kernel = clCreateKernel(program, "Limpid", &err);   
  149.     if (!kernel || err != CL_SUCCESS)   
  150.     {   
  151. printf("Error: Failed to create compute kernel!\n");   
  152.         exit(1);   
  153.     }   
  154.   
  155. // Create the input and output arrays in device memory for our calculation   
  156.     //   
  157.     input1 = clCreateBuffer(context,  CL_MEM_READ_ONLY,  sizeof(float) * count, NULL, NULL);   
  158.     input2 = clCreateBuffer(context,  CL_MEM_READ_ONLY,  sizeof(float) * count, NULL, NULL);   
  159.     output = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(float) * count, NULL, NULL);   
  160.     if (!input1 || !input2 || !output)   
  161.     {   
  162. printf("Error: Failed to allocate device memory!\n");   
  163.         exit(1);   
  164.     }       
  165.   
  166. // Write our data set into the input array in device memory    
  167.     //   
  168.     err = clEnqueueWriteBuffer(commands, input1, CL_TRUE, 0, sizeof(float) * count, image1, 0, NULL, NULL);   
  169.     err |= clEnqueueWriteBuffer(commands, input2, CL_TRUE, 0, sizeof(float) * count, image2, 0, NULL, NULL);   
  170.     if (err != CL_SUCCESS)   
  171.     {   
  172. printf("Error: Failed to write to source array!\n");   
  173.         exit(1);   
  174.     }   
  175.   
  176. // Set the arguments to our compute kernel   
  177.     //   
  178.     err = 0;   
  179.     err = clSetKernelArg(kernel, 0, sizeof(cl_mem), &input1);   
  180.     err |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &input2);   
  181.     err |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &output);   
  182.     if (err != CL_SUCCESS)   
  183.     {   
  184. printf("Error: Failed to set kernel arguments! %d\n", err);   
  185.         exit(1);   
  186.     }   
  187.   
  188. // Get the maximum work group size for executing the kernel on the device   
  189.     //   
  190.     err = clGetKernelWorkGroupInfo(kernel, device_id, CL_KERNEL_WORK_GROUP_SIZE, sizeof(local), &local, NULL);   
  191.     if (err != CL_SUCCESS)   
  192.     {   
  193. printf("Error: Failed to retrieve kernel work group info! %d\n", err);   
  194.         exit(1);   
  195.     }   
  196.     else   
  197. printf("The number of work items in a work group is: %lu\r\n", local);   
  198.   
  199. // Execute the kernel over the entire range of our 1d input data set   
  200. // using the maximum number of work group items for this device   
  201.     //   
  202.     global = count;   
  203.   
  204.     err = clEnqueueNDRangeKernel(commands, kernel, 2, NULL, (size_t[]){IMAGE_X_PIXELS, IMAGE_Y_PIXELS}, (size_t[]){22, 12}, 0, NULL, NULL);   
  205.     if (err)   
  206.     {   
  207. printf("Error: Failed to execute kernel!\n");   
  208. return EXIT_FAILURE;   
  209.     }   
  210.   
  211. // Wait for the command commands to get serviced before reading back results   
  212.     //   
  213.     clFinish(commands);   
  214.   
  215. // Read back the results from the device to verify the output   
  216.     //   
  217.     err = clEnqueueReadBuffer(commands, output, CL_TRUE, 0, sizeof(float) * count, results, 0, NULL, NULL );     
  218.     if (err != CL_SUCCESS)   
  219.     {   
  220. printf("Error: Failed to read output array! %d\n", err);   
  221.         exit(1);   
  222.     }   
  223.   
  224. // Validate our results   
  225.     //   
  226.     correct = 0;   
  227.     for(int i = 0; i < count; i++)   
  228.     {   
  229.         if(results[i] == image1[i] * IMAGE_SOURCE1_LIMPID  + image2[i] * IMAGE_SOURCE2_LIMPID)   
  230.             correct++;   
  231.     }   
  232.   
  233. // Print a brief summary detailing the results   
  234.     //   
  235. printf("Computed '%d/%d' correct values!\n", correct, count);   
  236.   
  237. // Shutdown and cleanup   
  238.     //   
  239. clReleaseMemObject(input1);   
  240. clReleaseMemObject(input2);   
  241. clReleaseMemObject(output);   
  242. clReleaseProgram(program);   
  243. clReleaseKernel(kernel);   
  244. clReleaseCommandQueue(commands);   
  245. clReleaseContext(context);   
  246.   
  247.  free(image1);   
  248.  free(image2);   
  249.  free(results);   
  250.   
  251.  return 0;   
  252. }  

附件:  OpenCL_init.zip (18 K) 下载次数:279

这里架构上与第二讲的Apple提供的示例代码差不多。但是,这边的内核函数要比之前的复杂一些。 这里输入有两个缓存数组,并且用了二维工作维度。我们首先看一下Limpid内核计算函数。 OpenCL中的C语言是ISO/IEC9899:1999标准的子集,因此兼容大多数C99的语法特性。我们在定义一个二维数组的时候必须要指定列数,函数可以忽略。这是C语言的一个特性。具体原因,可以在我的CSDN博客中找到答案。 这里的Limpid内核函数有两个输入数组,分别用来存放两个图像数据。我们分别对两个图像相应的每对像素做插值混合计算,将结果像素数据送给输出缓存。这里的像素是用一个单精度浮点来表示的;当然,我们也可以看作为是由4个单精度浮点组成。 这里我们通过调用get_global_id()来获得当前工作项第i维的id,对于二维工作组,每个二维ID(id_x, id_y)用于唯一标识一个工作项线程所对应的存储单元。对于二维工作组而言,第0维表示数据的列索引;而第1维则表示数据的行索引。如果我们将二维数组用一维索引来表示的话就是id_x + id_y * x_length;x_length表示一行有多少列。 我们分别获得当前行、列索引就能确定唯一的存储单元。我们可以对此进行操作。
然后我们再看第213行,对clEnqueueNDRangeKernel函数的调用。这里我们指定工作维度是2。然后,全局工作项的个数就分别是图像长度和高度;而一个工作组的大小这里是需要好好讲一下的。 由于我们之前通过clGetKernelWorkGroupInfo函数获得的工作组最大大小是512,而如果我们只用一个工作组的话就需要176 * 144个工作项,这个乘积已经大大超过512了。因此,我们可以对176 * 144进行划分,使得每个工作组的实际大小小于512。我们这里对一个工作组的行取了22,列取了12。那么对于二维工作组而言,工作组的个数就被划分为(8, 12)个。如果将整个计算资源看作为一个大的容器的话,那么它就有8 * 12个工作组;每个工作组有22 * 12个工作项。 如果各位有CUDA编程的一些概念的话,那么上面所说的工作组其实对应于Block;而上面所说的容器,其实就是一个Grid。这里再要提醒一下的是全局工作项的每个维度的个数都必须能够被所划分后的一个工作组的每个维度的工作项个数整除。

我们在主机端做数据组织的话可以不用考虑维度,都用一维的也没问题。包括数据创建以及读写。

 

下面为该程序加入了Profiling,并加入了1024 * 768的尺寸。在1024*768的情况下,工作组的X向可以含有32个工作项;Y向可以含有16个工作项。这样,X * Y正好等于512,能充分发挥GPU的效能。而此时,工作组集合就被划分成了(32, 48)。

附件:  OpenCL_Transparent.zip (26 K) 下载次数:42

 

下面提供更好的一个工程。这个工程里,OpenCL的内核做成文件资源,并且通过XCode能够显示出语法高亮,这样,内核代码就更容易阅读和修改,呵呵。 这里由于也是基于控制台的,因此在添加file copy的时候应该鼠标右键Copy Files,然后选择Get Info,将属性设置为 Resource,并在path里面空白。这样,在构造整个工程时,XCode会将你的kernel.cl作为资源文件拷贝到目标可执行文件的目录中去。

附件:  OpenCL_Basic.zip (20 K) 下载次数:42

0 0
原创粉丝点击