Opencv cpp:1557 error
Opencv实验中出现如下问题
ret2, th2 = cv.threshold(img, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
cv2.error: OpenCV(4.5.3) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-c2l3r8zm\opencv\modules\imgproc\src\thresh.cpp:1557: error: (-2:Unspecified error) in function ‘double __cdecl cv::threshold(const class cv::_InputArray &,const class cv::_OutputArray &,double,double,int)’
THRESH_OTSU mode:
‘src_type == CV_8UC1 || src_type == CV_16UC1’
where
‘src_type’ is 16 (CV_8UC3)
原代码如下
img = cv.imread('noisy.jpg')
# 固定阈值法
ret1, th1 = cv.threshold(img, 105, 255, cv.THRESH_BINARY)
# Otsu阈值法
ret2, th2 = cv.threshold(img, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
# 先进行高斯滤波,再使用Otsu阈值法
blur = cv.GaussianBlur(img, (5, 5), 0)
ret3, th3 = cv.threshold(blur, 105, 255, cv.THRESH_BINARY)
ret4, th4 = cv.threshold(blur, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
问题分析
cv2.threshold()函数是以单通道的形式输入图形,而我在上述的代码中的图像是以彩色三通道的形式输入,因此导致的错误。
解决方案
将彩色图片转变为单通道的灰度图片进行输入。
img = cv.imread('noisy.jpg',0)
重新运行程序
运行成功