Ask Your Question

cv::Mat incorrect reading binary data

asked 2013-10-28 11:55:47 -0500

biquaternion gravatar image

Hello! Help me, please. I try to read fits-file (astronomical image with 16-bit depth) into the cv::Mat structure, but a lot of bright pixels (brightness >= appr.0x8500) after reading become dark. It looks like register overflow, but the "threshold" = 0x8500 is far from maximal 16-bit value = 0xffff. The code is below:

unsigned short *c =, ..., ...); // file data maps to the memory on address c
cv::Mat im(cols, rows, CV_16U, c);  // after this a lot of image pixels (in im) is dark

Does anybody know why it's possible ? And how can I solve this trouble ? Thank you.

edit retag flag offensive close merge delete



btw, you got rows and cols wrong

tried to convert /scale it to 8bit again ?

Mat gr8; im.convertTo(gr8, CV_8U, 1.0/255);

if that looks ok, might be a flaw in imshow with 16bit

berak gravatar imageberak ( 2013-10-28 12:28:07 -0500 )edit

Thank you. The cols and rows is really not on their places - it's my misprint. It's not imshow flaw, because <im> contains bad pixels just after reading (I watch it, using debugger memory viewer - QtSDK). I have tried to convert, and saw the same result.

biquaternion gravatar imagebiquaternion ( 2013-10-29 07:03:55 -0500 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2013-11-14 14:12:29 -0500

biquaternion gravatar image

I've got answer. The problem was in byte order. When cv::Mat creates new image from allocated memory, it use little-endian byte order, while my data was mapped in big-endian.

edit flag offensive delete link more


Can you please comment on this, I have same trouble.

anatrong0 gravatar imageanatrong0 ( 2015-06-09 11:39:44 -0500 )edit

The data in my file was in big-endian style, while cv::Mat was constructed as that had got in little-endian style. That was the reason, why lower bytes were on places of higher bytes, and vice versa. Solution of this problem is to change byte order in data (in file or in memory) before constructing cv::Mat image.

biquaternion gravatar imagebiquaternion ( 2018-02-22 08:52:55 -0500 )edit

Question Tools

1 follower


Asked: 2013-10-28 11:55:47 -0500

Seen: 2,188 times

Last updated: Nov 14 '13