gpt4 book ai didi

python - 在 Python 中使用 findContours 和 OpenCV

转载 作者:太空宇宙 更新时间:2023-11-03 22:26:57 26 4
gpt4 key购买 nike

我在树莓派上使用 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)

我收到以下错误。

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

我已经尝试了一些其他设置并得到了同样的错误或者

ValueError: too many values to unpack

我正在使用 PiCamera。获得质心位置有什么建议吗?

谢谢

Z

最佳答案

错误一:

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

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

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

错误2

ValueError: too many values to unpack

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

此外,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."

关于python - 在 Python 中使用 findContours 和 OpenCV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36098241/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com