Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a pixel by Mat::at

Tags:

c++

opencv

I'm trying to get a pixel from a Mat object. To test I try to draw a diagonal line on a square and expect to get a perfect line crossing from the top left to the down right vertex.

for (int i =0; i<500; i++){
     //I just hard-coded the width (or height) to make the problem more obvious

  (image2.at<int>(i, i)) = 0xffffff;
     //Draw a white dot at pixels that have equal x and y position.
}

The result, however, is not as expected. Here is a diagonal line drawn on a color picture. enter image description here Here is it on a grayscale picture. enter image description here Anyone sees the problem?

like image 342
Max Avatar asked Jan 14 '23 02:01

Max


2 Answers

The problem is that you are trying to access each pixel as int (32 bit per pixel image), while your image is a 3-channel unsigned char (24 bit per pixel image) or a 1-channel unsigned char (8 bit per pixel image) for the grayscale one. You can try to access each pixel like this for the grayscale one

for (int i =0; i<image2.width; i++){
  image2.at<unsigned char>(i, i) = 255;
}

or like this for the color one

for (int i =0; i<image2.width; i++){     
      image2.at<Vec3b>(i, i)[0] = 255;
      image2.at<Vec3b>(i, i)[1] = 255;
      image2.at<Vec3b>(i, i)[2] = 255;
}
like image 106
Andrea Riccardi Avatar answered Jan 19 '23 12:01

Andrea Riccardi


(image2.at<int>(i, i)) = 0xffffff;

It looks like your color image is 24bit, but your addressing pixels in terms of int which seems to be 32 bit.

like image 26
sean3k Avatar answered Jan 19 '23 10:01

sean3k