在Python中使用OpenCV的问题

时间:2016-01-22 10:02:16

标签: python opencv

我正在尝试在我的Raspberry Pi上运行以下代码,但它给了我这个错误:

  

追踪(最近的呼叫最后):
    文件“video_capture_thresh.py”,第59行,中       main()
    在主要文件中输入第11行“video_capture_thresh.py”       crop = frame [180:320,0:638]
    TypeError:'NoneType'对象没有属性' getitem

import numpy as np
import cv2
#cap=cv2.VideoCapture(0)
cap = cv2.VideoCapture(1)

def main():
    while(True):
        # Capture frame-by-frame
        ret, frame = cap.read()
        # Our operations on the frame come here
        crop = frame[180:320, 0:638]
        crop2=cv2.cvtColor(crop,cv2.COLOR_BGR2GRAY)
        th,crop2 = cv2.threshold(crop2,0,255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
        previous = cv2.GaussianBlur(crop2, (5,5),0)
        contours, hierarchy = cv2.findContours(crop2,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
        cv2.rectangle(previous,(0,0),(638,140),(0,255,0),5) 
        i=0
        for cnt in contours:
            moments = cv2.moments(cnt)                          # Calculate moments
            if moments['m00']!=0:
                cx = int(moments['m10']/moments['m00'])         # cx = M10/M00
                cy = int(moments['m01']/moments['m00'])         # cy = M01/M00
                moment_area = moments['m00']                    # Contour area from moment
                contour_area = cv2.contourArea(cnt)             # Contour area using in_built function
                perimeter = cv2.arcLength(cnt,True)
                cv2.drawContours(previous, [cnt], 0, (0,255,0), 3)
                px = previous[cy,cx]
                if px == 255 :
                    i=i+1
                    cv2.circle(previous,(cx,cy),5,(0,0,255),-1)
        cv2.imshow("Previous",previous)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
main ()

cap.release()
cv2.destroyAllWindows()

2 个答案:

答案 0 :(得分:0)

尝试添加检查以确保在执行处理之前确实已经读好了

ret, frame = cap.read()
    if ret==True:
        crop = frame[180:320, 0:638]

答案 1 :(得分:0)

方法read

  

这是阅读视频文件或从解码中捕获数据并返回刚刚抓取的帧的最方便的方法。如果没有抓取帧(摄像机已断开连接,或视频文件中没有帧),则方法返回false,函数返回NULL指针。

检查相机是否从相机中捕获图像。

您使用的是哪种相机?

请注意,cv2.VideoCapture无法与Raspi模块相机配合使用,只适用于USB网络摄像头。