python:不支持图像的OpenCV深度(CV_64F)


问题内容

因此,我尝试使用此代码显示仅黑白图像的二进制图片:

import cv2
import numpy as np

x_img = cv2.imread("lenac.tif")

x_img_g = cv2.cvtColor(x_img, cv2.COLOR_BGR2GRAY)

y = x_img_g > 128

cv2.imshow("", y*1.0)
cv2.waitKey(0)
cv2.destroyAllWindows()

但我收到此错误:

>Traceback (most recent call last):
File "ex5.py", line 11, in <module>
cv2.imshow("", y*1.0)
cv2.error: OpenCV(4.0.0) c:\projects\opencv- 
python\opencv\modules\imgproc\src\color.hpp:261: error: (-2:Unspecified 
error) >in function '__cdecl cv::CvtHelper<struct 
cv::Set<1,-1,-1>,struct cv::Set<3,4,-1>,struct 
cv::Set<0,2,5>,2>::CvtHelper(const class cv::_InputArray &,const class 
cv::_OutputArray &,int)'
>Unsupported depth of input image:
>     'VDepth::contains(depth)'
> where
>     'depth' is 6 (CV_64F).

问题答案:

尝试cv2.imshow("", y.astype('float32'))cv2.imshow("", y.astype('uint8') * 255)

CV_64F表示numpy数组’dtype’是64位浮点opencv仅适用于’float32’(32位浮点),其中imshow的图像范围是0.0-1.0或’uint8’(无符号8位)0-255

由于y是布尔值,所以转换为数字意味着将True转换为1

对于float32,这很好,因为imshow范围的最大值为1

如果您使用uint8,则表示您尝试显示几乎不可见的值1/255的像素,因此您可以乘以255以使这些像素达到最大值并显示为亮白色像素