nburk
nburk

Reputation: 22731

Why does the OpenCV Mat object not contain the expected values after I assigned them in a nested for loop?

I am having trouble understanding how the Mat type in OpenCV works, and why it behaves the way it behaves in the following situation. Unfortunately, the docs that I have considered for this example don't help me much here...

Here is my program:

Mat matrix (5, 5, CV_16S);
matrix.setTo(0);

printf("matrix %d, %d: \n", matrix.cols, matrix.rows);
for( size_t i = 0; i < matrix.cols; i++ ) {
    for( size_t j = 0; j < matrix.rows; j++ ) {
        matrix.at<int>(i,j) = 200;
        printf( " %d ", matrix.at<int>(i,j));
    }
    printf("\n");
}
cout << "matrix: " << matrix << endl;

The first output that is generated within the nested for-loop gives me the results that I would expect, which is:

matrix 5, 5: 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200

This is because I created a Mat object with 5 rows and columns and assigned value 200 to each entry when looping over them.

However, the last line, where I use cout to print the Mat, gives me the following output:

matrix: [200, 0, 200, 0, 200;
  200, 0, 200, 0, 200;
  200, 0, 200, 0, 200;
  200, 0, 200, 0, 200;
  200, 0, 200, 0, 200]

Here, only every second entry is assigned to the value 200, unlike I would have expected. Can someone explain to me the logic behind this? What am I missing, what's causing the 0 entries, when before I have assigned each value in the matrix with 200?

Upvotes: 0

Views: 175

Answers (1)

berak
berak

Reputation: 39796

you're doing 2 things wrong there,

1) if your Mat is CV_16S, you have to access it as m.at<short>(r,c); (in other words, you at<type>() has to exactly match the Mat's type.)

2) it's row/col world in opencv, so if i goes over cols and j over rows, that must be: m.at<short>(j,i);

Upvotes: 2

Related Questions