Created
October 17, 2013 07:56
-
-
Save abidrahmank/7020863 to your computer and use it in GitHub Desktop.
RGB2Gray cpp file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <opencv2/core/core.hpp> | |
#include <opencv2/core/utility.hpp> | |
#include <opencv2/highgui/highgui.hpp> | |
#include <iostream> | |
#include <stdio.h> | |
#include <cuda.h> | |
#include <cuda_runtime.h> | |
using namespace std; | |
using namespace cv; | |
extern "C" void gray_parallel(unsigned char* h_in, unsigned char* h_out, int elems, int rows, int cols); | |
// My serial implementation, works fine | |
Mat gray_serial(Mat img){ | |
int rows = img.rows; | |
int cols = img.cols; | |
Mat gray(rows, cols, CV_8UC1); | |
for(int r=0; r<rows; r++){ | |
for(int c=0; c<cols; c++){ | |
Vec3b bgr = img.at<Vec3b>(r,c); | |
double gray_val = 0.144*bgr.val[0] + 0.587*bgr.val[1] + 0.299*bgr.val[2]; | |
gray.at<unsigned char>(r,c) = (unsigned char)gray_val; | |
} | |
} | |
return gray; | |
} | |
// One more serial code, just for testing, works fine | |
Mat gray_test(Mat img){ | |
cout << "running test" << endl; | |
uint rows = img.rows; | |
uint cols = img.cols; | |
unsigned char* test = img.data; | |
unsigned char* op = new unsigned char[rows*cols]; | |
for (uint i=0; i<rows*cols; i++){ | |
uint index = 3*i; | |
double temp = 0.144*test[index]+0.587*test[index+1]+0.299*test[index+2]; | |
op[i] = (unsigned char)temp; | |
} | |
Mat gray = Mat(rows, cols, CV_8UC1, op); | |
return gray; | |
} | |
// Main Function | |
int main( int argc, char** argv ) | |
{ | |
Mat image; | |
image = imread("baboon2.jpg"); // Read the file, it is simple 64x64 image. | |
// First trying serial code | |
int64 t1 = cv::getTickCount(); | |
Mat gray = gray_test(image); | |
int64 t2 = cv::getTickCount(); | |
cout << double(t2 - t1)/getTickCount() << " " << endl; | |
// Now trying GPU code | |
int64 t3 = cv::getTickCount(); | |
const int rows = image.rows; | |
const int cols = image.cols; | |
int elems = rows*cols*3; | |
unsigned char *h_in = image.data; | |
unsigned char *h_out = new unsigned char[rows*cols]; | |
gray_parallel(h_in, h_out, elems, rows, cols); | |
Mat gray2 = Mat(rows,cols,CV_8UC1,h_out); | |
int64 t4 = cv::getTickCount(); | |
cout << double(t4 - t3)/getTickCount() << " " << sizeof(unsigned char) << endl; | |
// Finally display result of GPU code (CPU code works fine, but not GPU code) | |
imshow("image.jpg",gray2); | |
waitKey(0); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment