简体   繁体   中英

Opening and saving a .bmp file changes bit depth

I have a file in bitmap format test.bmp . When looking at its properties, the bit depth of the file is 32. This is correct, as the file format is supposed to be RGBA.

For test purposes, I open this file using cv2 and then save it:

img_path = os.path.join(path_to_folder, "test.bmp")
img = np.array(cv2.imread(img_path, flags=cv2.IMREAD_UNCHANGED))

When I print the shape, I lose information on the alpha channel.

img.shape - (1200, 1920, 3)

I save the image again to see if the bit depth is conserved:

out_f_name = os.path.join(save_to_test, "test_save.bmp")
cv2.imwrite(out_f_name, img)

When looking at the bit depth of the saved image, I get 24 .

This is a problem as I need an output depth of 32 for further use.

I use version 4.7.0 of cv2

I have tried what you describe, but I'm not able to reproduce the error you are having, for me everithing works well. The original BMP with 4 channels is loaded correctly by OpenCV and when I write the image, the resulting one is with 32 bits depth.

here is my code:

import cv2 as cv
import numpy as np

img_path = "C:\\Users\\me\\Downloads\\snail4.bmp"
im = cv.imread(img_path, flags=cv.IMREAD_UNCHANGED)
print(im.shape)
(height, width, channels) = im.shape
cv.imshow('original', im)
for i in range(channels):
  s = im[:, :, i]
  cv.imshow(f'channel {i}',s)

cv.waitKey(0)
cv.destroyAllWindows()

cv.imwrite(img_path[:-4] + '_imwritten.bmp', im)

I have python 3.10.4, numpy==1.24.1 and opencv-python==4.7.0.68

hope that helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM