原程序
import cv2
import numpy as np
def cv_show(name, img):
cv2.imshow(name, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 读取图像
img = cv2.imread('contours.png')
cv_show('contours', img)
# 灰度化和二值化
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)[1]
cv_show('thresh', thresh)
# 寻找轮廓
cnt = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[1]
# 画出轮廓
draw = img.copy()
res = cv2.drawContours(draw, cnt, -1, (0, 0, 255), 2)
cv_show('res', res)
报错
Traceback (most recent call last):
File "C:/Users/ccccj/PycharmProjects/a_opencv/opencv/opencv_notebook/课件/第2-8节课件/第2-7节notebook课件/图像操作/contours.py", line 21, in
cnt = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[1]
cv2.error: OpenCV(3.4.11) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-7_3trius\opencv\modules\imgproc\src\contours.cpp:197: error: (-210:Unsupported format or combination of formats) [Start]FindContours supports only CV_8UC1 images when mode != CV_RETR_FLOODFILL otherwise supports CV_32SC1 images only in function 'cvStartFindContours_Impl'
原因:findContours()函数的src必须为灰度图,原程序使用的是img,改为如下结果
# 寻找轮廓
# cnt = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[1]
# 改为
cnt = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[1]