我正在使用有关开始使用轮廓的 OpenCV 3.0.0 beta 文档进行采样,并且在尝试使用文档中的轮廓代码时遇到了多个错误。我不知道如何解决这个问题,有人可以帮助我吗?
我从以下位置复制代码的文档:http: //docs.opencv.org/trunk/doc/py_tutorials/py_imgproc/py_contours/py_contours_begin/py_contours_begin.html#contours-getting-started
测试图片以应用轮廓:
http://www.k6-geometric-shapes.com/image-files/pyramid-base-rectangle.jpg
产生错误的代码行:
cv2.drawContours(img, contours, 3, (0,255,0), 3)
错误:
Traceback (most recent call last):
File "/home/anthony/Documents/Programming/Python/Computer-Vision/OpenCV-Doc/contour-draw.py", line 13, in <module>
cv2.drawContours(img, contours, 3, (0,255,0), 3)
error: /home/anthony/Downloads/opencv-3.0.0-beta/modules/imgproc/src/drawing.cpp:2160: error: (-215) 0 <= contourIdx && contourIdx < (int)last in function drawContours
还有另一个 drawContour 函数不起作用。一旦我注释掉上面的一个并在另一个函数(下面)中注释,它会产生不同的错误。
代码行:
cnt = contours[4]
cv2.drawContours(img, [cnt], 0, (0,255,0), 3)
错误:回溯(最近一次调用最后一次):文件“/home/anthony/Documents/Programming/Python/Computer-Vision/OpenCV-Doc/contour-draw.py”,第 15 行,在 cnt = contours[4] IndexError:列表索引超出范围
还有另外两个 drawContours 函数被注释掉了。有一个边框可以成功创建图片的轮廓,但由于某些原因,会产生窗口的轮廓。
代码:
import numpy as np
import cv2
img = cv2.imread('rectangle-pink.jpg')
imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
_,contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
#Displays the border
#cv2.drawContours(img, contours, -1, (0,255,0), 3)
cv2.drawContours(img, contours, 3, (0,255,0), 3)
#cnt = contours[4]
#cv2.drawContours(img, [cnt], 0, (0,255,0), 3)
cv2.imshow('Contour Pic', img)
cv2.waitKey(0)
cv2.destroyAllWindows()