我正在使用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)
错误: Traceback(最近一次调用最后一次): 文件“/home/anthony/Documents/Programming/Python/Computer-Vision/OpenCV-Doc/contour-draw.py”,第15行, cnt =等高线[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()
答案 0 :(得分:0)
在我的情况下,如果我在某个时候使用索引len(contours)-1
len(contours)
变为零并显示错误:
indexError:列表索引超出范围
如果我使用以下代码,一切正常。
if len(contours)>0 :
cnt=contours[len(contours)-1]
cv2.drawContours(img, [cnt], 0, (0,255,0), 3)