Using Mat::at with single channel image

asked 2014-01-05 17:00:09 -0600

zetain gravatar image

Hello,

i am trying to access the pixels of a single channel grayscale image. I am using this code:

for( int x = 1; x < binaryImage.cols; x++ )
{ 
for( int y = 1; y < binaryImage.rows; y++ )
    { 
     if(binaryImage.at<Vec3b>(x,y)[0] == 255)
     {
        redPixelsInCol[x] += 1;
        totalRedPixels++;
     }
     redCol[x] = redPixelsInCol[x] * x;
     }
 }

I get an error in VisualStudio telling me that i try to access memory i am forbidden to access. I can imagine that this is caused by the datatype Vec3b which forces the at-method to read 3 values every iteration. Due to the fact that a grayscale image only has one channel there aren't 3 values left at the end of the iteration so breaking the size of the mat object.

I am forced to specify the datatype in which the pixel value is returned but this must be an array or a pointer. Which type should i give the at-method for a single channel image? Or is there another reason causing this code to break?

thank you for your help :)

edit retag flag offensive close merge delete

Comments

3

hi, zetain, for a single channel img, access will be :

binaryImage.at<uchar>(x,y) == 255

in general, the type whithin the at<T> method has to match the image type

berak gravatar imageberak ( 2014-01-05 17:39:21 -0600 )edit
1

again, here's a short translation table:

  • CV_8U -> mat.at<uchar>(i,j)
  • CV_8UC3 -> mat.at<Vec3b>(i,j)
  • CV_32FC1 -> mat.at<float>(i,j)
  • CV_32FC3 -> mat.at<Vec3f>(i,j)

.. you'll get the picture !

berak gravatar imageberak ( 2014-01-05 17:46:16 -0600 )edit

ahhh! I am such an idiot. Thank you very much :)

zetain gravatar imagezetain ( 2014-01-06 04:19:34 -0600 )edit

mh ... I tried what you have proposed but it is still giving me the same error. My program runs perfectly when i use this line of code instead but is really slow:

binaryImage.col(x).row(y).data[0] == 255

so the rest of my program is not the problem. I also have checked if the picture has the amount of channels and the expected depth of 8Bit.

zetain gravatar imagezetain ( 2014-01-06 06:50:29 -0600 )edit

hehe, row(y) will return a whole row, also col(i). [that#s a lot of copying] . you want:

binaryImage.at<uchar>(y,x) == 255;

berak gravatar imageberak ( 2014-01-06 08:24:48 -0600 )edit