原文链接:http://www.juzicode.com/python-error-opencv-threshold-otsu-src-type-cv-8uc1-cv-16uc1
错误提示:
threshold使用THRESH_OTSU阈值化时提示src_type == CV_8UC1 || src_type == CV_16UC1
#VX公众号:桔子code / juzicode.com
import cv2
print('cv2.__version__:',cv2.__version__)
img = cv2.imread('lena.jpg')
thresh,img_bin = cv2.threshold(img,127,255, cv2.THRESH_BINARY|cv2.THRESH_OTSU)
print('thresh:',thresh)
cv2.imshow('img_bin',img_bin)
cv2.waitKey(0)
cv2.destroyAllWindows()
==========运行结果:
cv2.__version__: 4.5.2
---------------------------------------------------------------------------
error Traceback (most recent call last)
<ipython-input-24-a7626e630969> in <module>
3 print('cv2.__version__:',cv2.__version__)
4 img = cv2.imread('lena.jpg')
----> 5 thresh,img_bin = cv2.threshold(img,127,255, cv2.THRESH_BINARY|cv2.THRESH_OTSU)
6 print('thresh:',thresh)
7 cv2.imshow('img_bin',img_bin)
error: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-kuwfz3h3\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)
错误原因:
1、threshold用大津法做阈值处理时,输入的图像的深度只能是 CV_8UC1或 CV_16UC1,而这里是CV_8UC3。
解决方法:
1、在使用threshold前先用cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)将图像转换为单通道的灰度图:
#VX公众号:桔子code / juzicode.com
import cv2
print('cv2.__version__:',cv2.__version__)
img = cv2.imread('lena.jpg')
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # 转换为灰度图
thresh,img_bin = cv2.threshold(img,127,255, cv2.THRESH_BINARY|cv2.THRESH_OTSU)
print('thresh:',thresh)
cv2.imshow('img_bin',img_bin)
cv2.waitKey(0)
cv2.destroyAllWindows()
==========运行结果:
cv2.__version__: 4.5.2
thresh: 117.0
扩展内容:
如果本文还没有完全解决你的疑惑,你也可以在微信公众号“桔子code”后台给我留言,欢迎一起探讨交流。