I have a 2D numpy array which it's values are float between [-4, 3]. cv2.imshow shows this array as a BGR Image, but when I saved it with cv2.imwrite it was completely black. Then I found that I have to multiply the array to 255 to save it with imwrite, but in this case the image saved in RGB format, but I want to save the BGR image which shown by cv2.imshow. What should I do?
2
votes
Practically all image formats use RGB ordering. What format (file extension) do you want to use?
– Mark Setchell
I'm saving the image as a PNG file
– mhmmdrz92
PNG files are incapable of storing floats. You'll likely need TIFF or PFM.
– Mark Setchell
Also, the ordering within any image file you save (PNG, BMP, GIF, JPG) is not really relevant because OpenCV converts it on-the-fly as it reads or writes. The order is standardised to RGB so other applications can correctly interpret your images.
– Mark Setchell
Images in floating point format must have values in range [0,1]. Ones with 8 bit unsigned need to be in range [0,255]. Multiplying values in range [-4,3] by 255 will still leave you with invalid values (or worse, cause overflow, completely trashing the data.)
– Dan Mašek
2 Answers
1
votes
0
votes
First of all you have to adjust the value of all arrays. The pixels are between -4 and 3 so you have to do this:
img = img - min_val
img = img*255.0/(max_val - min_val)
which in your case it would be like:
img = img+4
img = img*255/7.0
then convert your img to 8bit unsinged int and save it with imwrite
(no need to mess with BGR or RGB, opencv handles it by itself)