How to save a binary image(with dtype=bool) using cv2?

21,664

Solution 1

You can use this:

cv2.imwrite('mask.png', maskimg * 255)

So this converts it implicitly to integer, which gives 0 for False and 1 for True, and multiplies it by 255 to make a (bit-)mask before writing it. OpenCV is quite tolerant and writes int64 images with 8 bit depth (but e. g. uint16 images with 16 bit depth). The operation is not done inplace, so you can still use maskimg for indexing etc.

Solution 2

Convert the binary image to the 'uint8' data type.

Try this:

>>> binary_image.dtype='uint8'
>>> cv2.imwrite('image.png', binary_image)

Solution 3

No OpenCV does not expects the binary image in the format of a boolean ndarray. OpenCV supports only np.uint8, np.float32, np.float64, Since OpenCV is more of an Image manipulation library, so an image with boolean values makes no sense, when you think of RGB or Gray-scale formats.

The most compact data type to store a binary matrix is uchar or dtype=np.uint8, So you need to use this data type instead of np.bool.

Share:
21,664
Vaibhav Dixit
Author by

Vaibhav Dixit

Updated on July 21, 2022

Comments

  • Vaibhav Dixit
    Vaibhav Dixit almost 2 years

    I am using opencv in python and want to save a binary image(dtype=bool). If I simply use cv2.imwrite I get following error:

    TypeError: image data type = 0 is not supported
    

    Can someone help me with this? The image is basically supposed to work as mask later.

  • Clay Records
    Clay Records over 5 years
    OP asked for a solution using CV2
  • Red Riding Hood
    Red Riding Hood over 4 years
    Seems to work also simply as: ` cv2.imwrite("mask.png", 255 * binary_image) `