通过Python中的程序捕获图像时出错

时间:2012-12-30 20:00:54

标签: opencv python-2.6

我是Python opencv的新手。任何人都可以帮我解决错误

import cv

cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE)
camera_index = 1
capture = cv.CaptureFromCAM(camera_index)

def repeat():
global capture #declare as globals since we are assigning to them now    global camera_index
frame = cv.QueryFrame(capture)
cv.ShowImage("w1", frame)
c = cv.WaitKey(100)
if(c=="n"): #in "n" key is pressed while the popup window is in focus
    camera_index += 1 #try the next camera index
    capture = cv.CaptureFromCAM(camera_index)
    if not capture: #if the next camera index didn't work, reset to 0.
        camera_index =1
        capture = cv.CaptureFromCAM(camera_index)

while True:
repeat()

这是我得到的错误 -

OpenCV Error: Null pointer (NULL array pointer is passed) in cvGetMat, file /home/paraste/OpenCV-2.3.1/modules/core/src/array.cpp, line 2382
Traceback (most recent call last):
  File "dualcamara.py", line 10, in <module>
img = cv.GetMat(cv.QueryFrame(capture), 500)
cv2.error: NULL array pointer is passed

2 个答案:

答案 0 :(得分:1)

似乎cv.CaptureFromCAM()cv.QueryFrame()失败(可能camera_index错误?),因此frame中的NULL会导致错误。您应该检查这两个函数的结果并确保它们成功(我只是在这种情况下打印一条消息,你当然可以做其他的事情):

capture = cv.CaptureFromCAM(camera_index)
if not capture:
     print "Failed to initialize capture"

frame = cv.QueryFrame(capture)
if not frame:
     print "Failed to get frame"

答案 1 :(得分:0)

cv.QueryFrame()可能会返回None,而您没有处理这种可能性。 我发现cv.QueryFrame()有时会在开头返回None,所以我只是简单地说:

if frame == None:
    return

这样,即使您的第一次呼叫失败,或者呼叫间歇性失败,您的循环也会继续并在捕获图像时提供图像。我使用python 2.7在Mac Book Pro上遇到了同样的问题,这为我解决了这个问题。