在Python中结合OpenCV使用findContours

2024-09-30 14:32:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我在raspberry pi上使用OpenCV并用Python构建。尝试制作一个简单的物体跟踪器,通过对图像进行阈值化并找到轮廓来定位质心,从而使用颜色来找到物体。当我使用以下代码时:

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)

我得到以下错误。在

^{pr2}$

我尝试了一些其他设置,但得到了相同的错误或

ValueError: too many values to unpack

我用的是皮卡默拉。有什么建议来确定质心位置吗?在

谢谢

Z


Tags: 定位图像image错误pi阈值cv2opencv
1条回答
网友
1楼 · 发布于 2024-09-30 14:32:52

错误1:

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

简单地说,cv2.findContours()方法在给定图像中没有找到任何轮廓,因此建议在访问轮廓之前进行一次健全性检查,如下所示:

^{pr2}$

错误2

ValueError: too many values to unpack

此错误是由于_,contours,_ = cv2.findContours引起的,因为cv2.findContours只返回2个值、轮廓和层次结构,因此很明显,当您试图从cv2.findContours返回的2个元素元组中解压3个值时,它将引发上述错误。在

另外,cv2.findContours会改变输入mat的位置,因此建议将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."

相关问题 更多 >