Extra zeros in OpenCV Mat

时间:2016-04-04 17:15:26

标签: c++ opencv

Tried building 'cv::Mat' from 2D array but I find that extra zeros are added to the Mat which I am not able to understand. The code I tried is :

int a2D [7][7];
for(loop condition)
{
   a2D[x][y] = value;
   cout << "Value :"<< value << endl;
}
Mat outmat = Mat(7, 7, CV_8UC1, &a2D);
cout << "Mat2D : "<< outmat  << endl;

Output is :

Value : 22
Value : 179
Value : 145
Value : 170
Value : 251
Value : 250
Value : 171
Value : 134
Value : 218
Value : 178
Value : 6
....Upto 49 values.
Mat2D : [ 22,   0,   0,   0, 179,   0,   0;
   0, 145,   0,   0,   0, 170,   0;
   0,   0, 251,   0,   0,   0, 250;
   0,   0,   0, 171,   0,   0,   0;
 134,   0,   0,   0, 218,   0,   0;
   0, 178,   0,   0,   0,   6,   0;
   0,   0,  72,   0,   0,   0,  25]

As in Mat2D output after every value 3 zeros are added.Why and how?

2 个答案:

答案 0 :(得分:2)

You are using int buffer to initialize cv::Mat with unsigned char elements, that explains why values are written at each fourth element (int seems to be 4 times larger than unsigned char on your machine).

Changing type of a2D to unsigned char should fix the issue.

答案 1 :(得分:0)

The assignment a2D[x][y] = value is wrong if the type of a2D is int[49], you are writing outside the array. The 0's you see are uninitialized garbage.

You have to access a2D with a single index. For example: a2D[i] = value.