简体   繁体   English

在OpenCV中使用Python中的findContours

[英]Using findContours in Python with OpenCV

I'm using OpenCV on the raspberry pi and building with Python. 我在树莓派上使用OpenCV并使用Python构建。 Trying to make a simple object tracker that uses color to find the object by thresholding the image and finding the contours to locate the centroid. 尝试制作一个简单的对象跟踪器,该对象跟踪器使用颜色通过阈值化图像并找到轮廓以定位质心来找到对象。 When I use the following code: 当我使用以下代码时:

image=frame.array
imgThresholded=cv2.inRange(image,lower,upper)    
_,contours,_=cv2.findContours(imgThresholded,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnt=contours[0]
Moments = cv2.moments(cnt)
Area = cv2.contourArea(cnt)

I get the following error. 我收到以下错误。

Traceback (most recent call last):
 File "realtime.py", line 122, in <module>
  cnt=contours[0]
IndexError: list index out of range

I've tried a few other settings and get the same error or 我尝试了其他一些设置,但得到相同的错误,或者

ValueError: too many values to unpack

I'm using the PiCamera. 我正在使用PiCamera。 Any suggestions for getting centroid position? 对获得质心位置有任何建议吗?

Thanks 谢谢

Z ž

Error 1: 错误1:

Traceback (most recent call last):
 File "realtime.py", line 122, in <module>
  cnt=contours[0]
IndexError: list index out of range

Simply stands that the cv2.findContours() method didn't found any contours in the given image, so it is always suggested to do a sanity checking before accessing the contour, as: 简单地说, cv2.findContours()方法在给定图像中未找到任何轮廓,因此始终建议在访问轮廓之前进行完整性检查,如下所示:

if len(contours) > 0:
    # Processing here.
else:
    print "Sorry No contour Found."

Error2 误差2

ValueError: too many values to unpack

This error is raised due to _,contours,_ = cv2.findContours , since the cv2.findContours returns only 2 values, contours and hierarchy, So obviously when you try to unpack 3 values from 2 element tuple returned by the cv2.findContours , it would raise the above mentioned error. 由于_,contours,_ = cv2.findContours引发此错误,因为cv2.findContours仅返回2个值,轮廓和层次结构,所以很显然,当您尝试从cv2.findContours返回的2个元素元组中解压缩3个值时,这将引发上述错误。

Also the cv2.findContours changes the input mat in place, so it is suggested to call the cv2.findContours as: 另外, cv2.findContours会在适当位置更改输入垫,因此建议将cv2.findContours调用为:

contours, hierarchy = cv2.findContours(imgThresholded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if len(contours) > 0:
    # Processing here.
else:
    print "Sorry No contour Found."

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM