# Convert a 2D array to Mat (OpenCV) using C++, but the output of the Mat is wrong

I am trying to convert a simple 2D array to Mat in C++, but when I output Mat it shows that it is filling the matrix by skipping an element.

int size = 3;
static unsigned int x [3][3];
for (int i = 0; i <size;i++){
for(int j = 0; j <size; j++){
x[i][j] = 255*3;
std::cout << x[i][j]<<' ' << 'x'<<std::endl;
}
}
cv::Mat A(size,size, CV_16U,x);
std::cout<< A<<' '<<std::endl;


Output:

765 x 765 x 765 x 765 x 765 x 765 x 765 x 765 x 765 x

[765, 0, 765; 0, 765, 0; 765, 0, 765]

Another example I tried:

int x[6] = {2,4,8,9,6,5};
cv::Mat A (2,3, CV_16U,x);
std::cout<< A<<' '<<std::endl;


Output:

[2, 0, 4; 0, 8, 0]

Can anyone please tell me what I am doing wrong, thanks.

edit retag close merge delete

Sort by ยป oldest newest most voted

it's a simple type error. your x is unsigned int, while you treat the Mat as unsigned short.

there is no support for unsigned int in opencv, so you're gonna need:

int size = 3;
static unsigned short x[3][3];
...
cv::Mat A(size,size, CV_16U,x);
// and careful here, A is only valid as long as x stays in scope !

more

thank you.

( 2019-12-30 06:14:30 -0500 )edit

Official site

GitHub

Wiki

Documentation

## Stats

Asked: 2019-12-30 06:02:03 -0500

Seen: 129 times

Last updated: Dec 30 '19