Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

opencv

cv2

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.

like image 891
Vaibhav Dixit Avatar asked Jun 16 '17 11:06

Vaibhav Dixit


People also ask

How do I save an image in cv2?

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.

How do you create a binary image in Python?

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.

How do you Binarize an image?

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 .

How do you use Imread in Python?

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.


2 Answers

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.

like image 68
John Avatar answered Sep 19 '22 14:09

John


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

Try this:

>>> binary_image.dtype='uint8'
>>> cv2.imwrite('image.png', binary_image)
like image 29
avereux Avatar answered Sep 17 '22 14:09

avereux