计算RGB图像的直方图
// kernel __kernel void histogram(__global uchar* imgdata, __global uint *histogram, __local uint *local_histogram, uint data_size_item, uint all_byte_size) { // 对局部数据进行初始化 for(uchar i =0;i<32;i++) { local_histogram[0]=0; } barrier(CLK_LOCAL_MEM_FENCE);// 局部同步 int item_offset = get_global_id(0) * data_size_item *3; // 遍历该工作项所处理的数据 for(int i = item_offset;i<item_offset+data_size_item *3&&i<all_byte_size;i+=3) { // B atomic_inc(local_histogram+imgdata[i]/8+64); // G atomic_inc(local_histogram+imgdata[i+1]/8+32); // R atomic_inc(local_histogram+imgdata[i+2]/8); } barrier(CLK_GLOBAL_MEM_FENCE); // 全局同步 // 归并 int i = get_local_id(0); if(i < 96) { atomic_add(histogram+i,local_histogram[i]); } }
#include <iostream> #include <opencv2/opencv.hpp> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #ifdef __APPLE__ #include <OpenCL/opencl.h> #else #include <CL/cl.h> #endif const char histogram_cl_kernel_filename[]= "histogram.cl"; /** * 获取设备 * @return cl_device_id */ cl_device_id getdevice() { cl_platform_id platform; cl_device_id dev; int err; // 获取一个平台 err = clGetPlatformIDs(1,&platform,NULL); if(err<0) { perror("获取平台失败!"); exit(1); } // 获取一个GPU设备 err=clGetDeviceIDs(platform,CL_DEVICE_TYPE_GPU,1,&dev,NULL); if(err<0) { perror("获取设备失败!"); exit(1); } return dev; } /** * 创建并编译程序 * cl_context ctx:上下文 * cl_device_id dev : 设备 * filename: 文件名称 * @return cl_program */ cl_program build_program(cl_context ctx, cl_device_id dev,const char* filename) { cl_program program; FILE *program_handle; char *program_buffer ,*program_log; size_t program_size, log_size; int err; // 从文件中读取程序内容 program_handle = fopen(filename,"r"); if(program_handle == NULL) { perror("程序文件无法打开!"); exit(1); } fseek(program_handle,0,SEEK_END); program_size=ftell(program_handle); rewind(program_handle); program_buffer = (char*)malloc(program_size + 1); program_buffer[program_size] = '