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.
Write an Image (cv2. To save an image into the file directory, we use the imwrite(filename, img) function. The function takes 2 arguments. The first argument is the file name. The function chooses the image format from the file name extension.
Approach: Read the image from the location. As a colored image has RGB layers in it and is more complex, convert it to its Grayscale form first. Set up a Threshold mark, pixels above the given mark will turn white, and below the mark will turn black.
You can binarize an image with cv2. threshold() . If type is set to cv2. THRESH_BINARY , any value greater than the threshold thresh is replaced with maxval and the other values are replaced with 0 .
imread() method loads an image from the specified file. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format) then this method returns an empty matrix. Parameters: path: A string representing the path of the image to be read.
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.
Convert the binary image to the 'uint8' data type.
Try this:
>>> binary_image.dtype='uint8'
>>> cv2.imwrite('image.png', binary_image)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With