我读取图像,并使用此功能将其转换为灰度:
def rgb2gray(img):
if len(img.shape)==3 & img.shape[-1] == 3: # img is RGB
return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
return img
现在,我尝试使用此图像将图像转换为二进制图像:
def apply_threshold(img):
if len(np.unique(img))==2: #img is already binary
return img
gray_img=rgb2gray(img)
_,binary_img=cv2.threshold(gray_img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
return binary_img
但是我收到这个烦人的错误:
cv2.error: OpenCV(3.4.1) C:\projects\opencv-python\opencv\modules\imgproc\src\thresh.cpp:1406: error: (-215) src.type() == (((0) & ((1 << 3) - 1)) + (((1)-1) << 3)) in function cv::threshold
我不明白为什么,因为gray_img
肯定是灰度的!我查看了this问题,salvador daly
的最高答案提出输入图片不是灰度的,但我对其进行了多次检查,并确定是。]
任何帮助将不胜感激!
我读取图像,并使用以下功能将其转换为灰度:def rgb2gray(img):如果len(img.shape)== 3&img.shape [-1] == 3:#img为RGB返回cv2.cvtColor(img,cv2 ....
您可以尝试这种方法来获取彩色图像的阈值版本/二进制图像。