Reputation: 894
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.
Upvotes: 16
Views: 35906
Reputation: 607
Convert the binary image to the 'uint8' data type.
Try this:
>>> binary_image.dtype='uint8'
>>> cv2.imwrite('image.png', binary_image)
Upvotes: 2
Reputation: 1834
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.
Upvotes: 26
Reputation: 1
If you are using OpenCV, you should consider using hsv format for threshing the image. Convert the BGR image to HSV using cv2.cvtColor()
and then threshold your image using cv2.inRange()
function.
You would need values for the upper and lower limits for Hue(h), Saturation(s) and Value(v). For this you may use this script or create your own using it as reference.
This script is meant to return hsv lower and upper limit values for live video stream input but with minor adjustments, you can do the same with image inputs as well.
Save the obtained binary(kind of) image using cv2.imwrite()
, and there you have it. You may use this binary image for masking too. If you are still left with any doubts, you may refer to this script and it should clear most of them.
Upvotes: -1
Reputation: 1041
ndarray.astype('bool')
See this page may help:
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.astype.html
Upvotes: -1
Reputation: 22954
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
.
Upvotes: 2