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

Vaibhav Dixit picture Vaibhav Dixit · Jun 16, 2017 · Viewed 16k times · Source

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.

Answer

John picture John · Jul 16, 2018

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.