Get the device context Create GPU array/vector Copy the image & set up the kernel Execute the kernel Copy GPU data back to CPU cv::Mat data pointer OpenCV conversion for convienient display
| 125 | //Copy GPU data back to CPU cv::Mat data pointer |
| 126 | //OpenCV conversion for convienient display |
| 127 | void calculateHistogramUsingCL(cv::Mat src, compute::command_queue &queue) |
| 128 | { |
| 129 | compute::context context = queue.get_context(); |
| 130 | |
| 131 | // Convert image to BGRA (OpenCL requires 16-byte aligned data) |
| 132 | cv::cvtColor(src, src, CV_BGR2BGRA); |
| 133 | |
| 134 | //3 channels & 256 bins : alpha channel is ignored |
| 135 | compute::vector<int> gpu_b_hist(histSize, context); |
| 136 | compute::vector<int> gpu_g_hist(histSize, context); |
| 137 | compute::vector<int> gpu_r_hist(histSize, context); |
| 138 | |
| 139 | // Transfer image to gpu |
| 140 | compute::image2d gpu_src = |
| 141 | compute::opencv_create_image2d_with_mat( |
| 142 | src, compute::image2d::read_only, |
| 143 | queue |
| 144 | ); |
| 145 | |
| 146 | compute::program histogram_program = |
| 147 | compute::program::create_with_source(source, context); |
| 148 | histogram_program.build(); |
| 149 | |
| 150 | // create histogram kernel and set arguments |
| 151 | compute::kernel histogram_kernel(histogram_program, "histogram"); |
| 152 | histogram_kernel.set_arg(0, gpu_src); |
| 153 | histogram_kernel.set_arg(1, gpu_b_hist.get_buffer()); |
| 154 | histogram_kernel.set_arg(2, gpu_g_hist.get_buffer()); |
| 155 | histogram_kernel.set_arg(3, gpu_r_hist.get_buffer()); |
| 156 | |
| 157 | // run histogram kernel |
| 158 | // each kernel thread updating red, green & blue bins |
| 159 | size_t origin[2] = { 0, 0 }; |
| 160 | size_t region[2] = { gpu_src.width(), |
| 161 | gpu_src.height() }; |
| 162 | |
| 163 | queue.enqueue_nd_range_kernel(histogram_kernel, 2, origin, region, 0); |
| 164 | |
| 165 | //Make sure kernel get executed and data copied back |
| 166 | queue.finish(); |
| 167 | |
| 168 | //create Mat and copy GPU bins to CPU memory |
| 169 | cv::Mat b_hist(256, 1, CV_32SC1); |
| 170 | compute::copy(gpu_b_hist.begin(), gpu_b_hist.end(), b_hist.data, queue); |
| 171 | cv::Mat g_hist(256, 1, CV_32SC1); |
| 172 | compute::copy(gpu_g_hist.begin(), gpu_g_hist.end(), g_hist.data, queue); |
| 173 | cv::Mat r_hist(256, 1, CV_32SC1); |
| 174 | compute::copy(gpu_r_hist.begin(), gpu_r_hist.end(), r_hist.data, queue); |
| 175 | |
| 176 | b_hist.convertTo(b_hist, CV_32FC1); //converted for displaying |
| 177 | g_hist.convertTo(g_hist, CV_32FC1); |
| 178 | r_hist.convertTo(r_hist, CV_32FC1); |
| 179 | |
| 180 | showHistogramWindow(b_hist, g_hist, r_hist, "Histogram"); |
| 181 | } |
| 182 | |
| 183 | int main( int argc, char** argv ) |
| 184 | { |
no test coverage detected