检测轮廓并显示错误

时间:2016-04-06 07:11:33

标签: python opencv image-processing shadow

我尝试删除带阈值的阴影并检测实时相机上的动作。 这是我的计划:

import cv2
import numpy as np

cam = cv2.VideoCapture(0)

while True:

    t=cam.read()[1]
    t0=cv2.cvtColor(cam.read()[1],cv2.COLOR_RGB2GRAY)
    t1=cv2.cvtColor(cam.read()[1],cv2.COLOR_RGB2GRAY)
    t2=cv2.cvtColor(cam.read()[1],cv2.COLOR_RGB2GRAY)

    a1=cv2.absdiff(t0,t1)
    a2=cv2.absdiff(t1,t2)
    b=cv2.bitwise_and(a1,a2)

    ret,thresh0=cv2.threshold(b,30,255,cv2.THRESH_BINARY)
    thresh1=cv2.bitwise_and(t1,thresh0)
    contours,hierarchy=cv2.findContours(thresh0,1,2)
    cnt=contours[0]
    x,y,w,h=cv2.boundingRect(cnt)
    img=cv2.rectangle(t1,(x,y),(x+w,y+h),(0,255,0),2)

    cv2.imshow("winName",t1)
    cv2.imshow("detect",img)


    key=cv2.waitKey(10)
    if key==27:
        cv2.destroyAllwindow()
        break
print "End"

但我遇到以下错误:

in line ( cv2.imshow("detect",img) ) which stop with this error : 
    cv2.imshow("thresh",img)

error: /home/rayannik/opencv-2.4.10/modules/highgui/src/window.cpp:261:    
error: (-215) size.width>0 && size.height>0 in function imshow

如果我们忽略该行,那么只有当某些东西总是在相机前面移动时它才会起作用,否则会因此错误而停止:

cnt=contours[0]
IndexError: list index out of range

1 个答案:

答案 0 :(得分:0)

问题在于:

img=cv2.rectangle(t1,(x,y),(x+w,y+h),(0,255,0),2)

基本上cv2.rectangle()方法就地更改输入mat并返回None,因此参数t1就地修改,因为返回类型为None ,因此img中使用的变量imshow()None

删除cv2.imshow("detect",img),因为更改已反映在cv2.imshow("winName",t1)窗口中。

其次,cnt=contours[0]引发IndexOutOfBounds错误,因为cv2.findCountours()在输入Mat中找不到任何轮廓。您必须始终只将 BinaryImage 传递给cv2.findCountours方法,并在访问计数之前进行检查:

if (len(contours) > 0):  # this condition would prevent the IndexOutOfBounds error
    cnt=contours[0]