Ask Your Question
0

Need explanation for the following! thanks in advance.

asked 2020-07-28 09:15:17 -0500

Jagadeesh1993 gravatar image

I have the following block of code in main function in C++. I am using openCV 4.1.1.

int a[ ] = { 1,2,3,4,5,6,7,8,9 };

Mat matrix(1, 9, CV_8SC1, &a);

cout<< matrix<<endl;< p="">

The expected output is:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

But the actual output is:

[ 1, 0, 0, 0, 2, 0, 0, 0, 3]

I am able to get the desired output by using the following statement!

Mat matrix(1, 9, CV_32SC1, &a);

Can someone please provide explanation for why CV_8SC1 is not giving the desired output, also provide references if possible. Thanks in advance.

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted
0

answered 2020-07-28 11:39:55 -0500

berak gravatar image

on a 32bit system an int takes the same space as 4 bytes. so, if you set the type of the Mat header to CV_8S, it only considers the first 9 bytes in memory.

char a[ ] = { 1,2,3,4,5,6,7,8,9 };
Mat matrix(1, 9, CV_8SC1, &a);

(char array instead of int) would have been, what you wanted there.

in the end, you have to be very careful, using a Mat constructor with external data like above. apart from the type problem, this type of Mat is NOT refcounted, and once your initial data goes out of scope, your Mat is invalid ("dangling pointer")

edit flag offensive delete link more
1

answered 2020-07-28 10:04:17 -0500

mvuori gravatar image

8S is really a char, but you are feeding the Mat a buffer of ints - which in 32 bit program are 32Ss...

edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower

Stats

Asked: 2020-07-28 09:15:17 -0500

Seen: 54 times

Last updated: Jul 28