2
votes

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
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 filemhmmdrz92
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

So, basically you want to convert your image from RGB to BGR image.

This can be done by using cv2.cvtColor() function.

result_BGR = cv2.cvtColor(RGB_image, cv2.COLOR_RGB2BGR)
cv2.imwrite('PATH', result_BGR)
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)