harry lakins
harry lakins

Reputation: 843

Why do I get different values when using different datatypes when accessing pixels in a matrix?

I have a single channel grayscale image (slice).

    cout << "num" << slice.channels() << ends; //outputs 1
    for(int x = 0;x<=slice.cols;x++){
        for(int y = 0;y<=slice.rows;y++){
            Vec3b currentPoint = slice.at<Vec3b>(x,y);
            cout << currentPoint;
        }
    }

however, when I try to access a pixel and expect currentPoint to be a single int as it is a single channel image. However, i get [32, 36, 255] which is odd, as it implies three channels. I appreciate I am using a type that says vec3b, but even so, where is it getting the other two elements from?

So I replace Vec3b with uchar, then i get lots of \377. That is even more confusing.

Even when I do have a 3 channel image, I get odd outputs when trying to access a single element of Vec3b (i get more \377).

How can this make sense? I must be mis understanding how the at() method is used.

Firstly, how do I get a single output for each pixel (0-255)?

Also, where am I going wrong when i see \377?

Upvotes: 0

Views: 66

Answers (1)

Miki
Miki

Reputation: 41765

A lot of stuff for a few lines of code...

  • Since your image is a grayscale image, you should access it with at<uchar>.
  • Pay attention that the at<> function accepts (rows, cols), which is the opposite of (x,y).
  • It's faster to scan by line, since the matrix is stored row-wise in memory.
  • To print out the value of a uchar, you need to cast to int, or you get the ASCII coded character.
  • The loops should not be <=, but instead <, or you go out of bounds.

So:

for(int y = 0; y < slice.rows; y++) {
    for(int x = 0; x < slice.cols; x++) {
        uchar currentPoint = slice.at<uchar>(y,x);
        cout << int(currentPoint) << " ";
    }
    cout << "\n";
}

Upvotes: 4

Related Questions