Guest User

Untitled

a guest
Dec 9th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. #include <iostream>
  2. #include <cuda.h>
  3. #include <cuda_runtime.h>
  4. #include <opencv2/core/core.hpp>
  5. #include <opencv2/highgui/highgui.hpp>
  6. #include <opencv2/imgproc/imgproc.hpp>
  7.  
  8. using namespace cv;
  9. using namespace std;
  10.  
  11. __global__ void rgba_to_greyscale(const uchar4* const rgbaImage,
  12. unsigned char* greyImage,
  13. int numRows, int numCols)
  14. {
  15. int col = blockIdx.x * blockDim.x + threadIdx.x;
  16. int row = blockIdx.y * blockDim.y + threadIdx.y;
  17.  
  18. if (col >= numCols || row >= numRows) {
  19. return;
  20. }
  21.  
  22. int offset = row * numCols + col;
  23.  
  24. uchar4 rgba_pixel = rgbaImage[offset];
  25. float greyness = .299f * rgba_pixel.x + .587f * rgba_pixel.y +
  26. .114f * rgba_pixel.z;
  27. greyImage[offset] = static_cast<unsigned char>(greyness);
  28. }
  29.  
  30. int main()
  31. {
  32. Mat imageRGBA;
  33. Mat imageGrey;
  34. uchar4 *h_rgbaImage;
  35. uchar4 *d_rgbaImage = NULL;
  36. unsigned char *h_greyImage;
  37. unsigned char *d_greyImage = NULL;
  38. ///////////////////////////////////
  39. Mat image;
  40. image = cv::imread("IMG.jpg");
  41. if (image.empty()) {
  42. cerr << "Couldn't open file: " << endl;
  43. exit(1);
  44. }
  45.  
  46. ///////////////////////////////////
  47. int numRows = image.rows;
  48. int numCols = image.cols;
  49. ///////////////////////////////////////
  50. cvtColor(image, imageRGBA, COLOR_BGR2RGBA);
  51.  
  52. //Allocate Memory for output
  53. imageGrey.create(image.rows, image.cols, CV_8UC1);
  54. h_rgbaImage = (uchar4 *)imageRGBA.data;
  55. h_greyImage = (unsigned char *)imageGrey.data;
  56.  
  57. const size_t numPixels = numRows * numCols;
  58.  
  59. //Allocate memory on the device for both input and output
  60.  
  61. cudaMalloc((void**)d_rgbaImage, sizeof(uchar4) * numPixels);
  62. cudaMalloc((void**)d_greyImage, sizeof(unsigned char) * numPixels);
  63. cudaMemset((void *)d_greyImage, 0, numPixels * sizeof(unsigned char));
  64. //Copy input array to the GPU
  65.  
  66. cudaMemcpy(d_rgbaImage, h_rgbaImage, sizeof(uchar4)*numPixels,
  67. cudaMemcpyHostToDevice);
  68.  
  69. //Calling the Kernel -
  70.  
  71. const dim3 blockSize(32, 16, 1);
  72. const dim3 gridSize(1 + (numCols / blockSize.x), 1 + (numRows /
  73. blockSize.y), 1);
  74.  
  75. rgba_to_greyscale <<<gridSize, blockSize >>> (d_rgbaImage, d_greyImage,
  76. numRows, numCols);
  77.  
  78. //Copy Output array to Host
  79.  
  80. cudaMemcpy(h_greyImage, d_greyImage, sizeof(unsigned char) * numPixels,
  81. cudaMemcpyDeviceToHost);
  82.  
  83. //Check Output
  84. Mat output;
  85. output = Mat(numRows, numCols, CV_8UC1, (void*)h_greyImage);
  86. imwrite("result.jpg", output);
  87. }
Add Comment
Please, Sign In to add comment