Ask Your Question
1

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

asked 2019-12-30 06:02:03 -0600

IIVirusII gravatar image

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 flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2019-12-30 06:10:12 -0600

berak gravatar image

updated 2019-12-30 06:11:12 -0600

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 !
edit flag offensive delete link more

Comments

thank you.

IIVirusII gravatar imageIIVirusII ( 2019-12-30 06:14:30 -0600 )edit

Question Tools

1 follower

Stats

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

Seen: 4,560 times

Last updated: Dec 30 '19