原文链接:http://www.juzicode.com/python-error-opencv-thresh-triangle-error-215-src-type-cv-8uc1
错误提示:
OpenCV threshold使用THRESH_TRIANGLE阈值化时提示error: (-215:Assertion failed) src.type() == CV_8UC1
#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_TRIANGLE)
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-27-341416a0c0eb> 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_TRIANGLE)
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:1563: error: (-215:Assertion failed) src.type() == CV_8UC1 in function 'cv::threshold'
错误原因:
1、threshold的type参数使用三角法标志位做阈值处理时,输入的图像的深度只能是 CV_8UC1,而这里是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')
thresh,img_bin = cv2.threshold(img,127,255, cv2.THRESH_BINARY|cv2.THRESH_TRIANGLE)
print('thresh:',thresh)
cv2.imshow('img_bin',img_bin)
cv2.waitKey(0)
cv2.destroyAllWindows()
扩展内容:
如果本文还没有完全解决你的疑惑,你也可以在微信公众号“桔子code”后台给我留言,欢迎一起探讨交流。