在 Python 中使用 findContours 和 OpenCV [英] Using findContours in Python with OpenCV

查看:38
本文介绍了在 Python 中使用 findContours 和 OpenCV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using OpenCV on the raspberry pi and building with 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)

我收到以下错误.

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

我正在使用 PiCamera.获得质心位置的任何建议?

I'm using the PiCamera. Any suggestions for getting centroid position?

谢谢

Z

推荐答案

错误 1:

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

简单地认为 cv2.findContours() 方法没有在给定的图像中找到任何轮廓,因此总是建议在访问轮廓之前进行完整性检查,如:

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:

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 个值,它会引发上述错误.

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.

同样 cv2.findContours 改变了输入 mat,所以建议将 cv2.findContours 调用为:

Also the cv2.findContours changes the input mat in place, so it is suggested to call the cv2.findContours as:

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 中使用 findContours 和 OpenCV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆