I am trying to access openCV matrix element which comes from converting video frame into grayscale. My code is like this:
int C = 3;
cv::Mat grayPrevious;
cv::cvtColor ( previousFrame, grayPrevious, CV_RGB2GRAY );
double* grayPtr = grayPrevious.ptr <double> ();
double mean [600][800][3];
///... // set some values to mean here
for ( int i = 0; i < 600; i ++ )
{
for ( int j = 0; j < 800; j ++ )
{
for ( int m = 0; m < C; m ++ )
{
diff [i][j][m]= abs(grayPtr[ 800* (i-1)+j] - mean[i][j][m]);
}
}
}
But it crashes in the for loop. Is this something related to datatypes? How can I change it?
Besides, my second question is, I tried to see the elements of grayPrevious matrix on the screen using “grayPrevious.at”, but it shows values like ” -5.235125e+30″ for “double”, or “-11242433” for “int”. This is also confusing me, I was expecting to see values between 0 and 255.
You should use
ucharinstead ofintordoublesince you are dealing with grayscale images. (You can cast theucharto print:cout<<(int)grayPrevious.at<uchar>(i,j);)Is there any reason you are trying to access pixels directly “the hard way”?
You could do
grayprevious.at<uchar>(i,j)(assuming your image is 800×600) which is easier to debug and then use direct pixel access.Edit: I think it should be:
uchar* grayPtr = grayPrevious.ptr <uchar> ();and thengrayPtr[grayPrevious.cols*i+j];You could also do
grayPrevious.data[grayPrevious.cols*i+j];(Still direct access withoutptr)