问题描述
我在Macbook上使用OpenCV 2.4和python 2.7.5。我要使用以下代码显示内置摄像头的直播:
I'm using OpenCV 2.4 and python 2.7.5 on a macbook. I want to display the live stream of the inbuilt camera with the following code :
import cv
cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE)
camera_index = 0
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)
print type(frame)
#cv.ShowImage("w1", frame)
c = cv.WaitKey(10)
while True:
repeat()
但是,它似乎QueryFrame不总是返回一个iplimage,这里是我得到的终端:
However, it seems QueryFrame does not always return an iplimage, here is what I get on the terminal:
<type 'NoneType'>
<type 'NoneType'>
<type 'NoneType'>
<type 'NoneType'>
<type 'NoneType'>
<type 'NoneType'>
<type 'NoneType'>
<type 'NoneType'>
<type 'NoneType'>
<type 'NoneType'>
<type 'NoneType'>
<type 'NoneType'>
<type 'NoneType'>
<type 'NoneType'>
<type 'cv2.cv.iplimage'>
<type 'NoneType'>
<type 'NoneType'>
<type 'cv2.cv.iplimage'>
<type 'NoneType'>
<type 'NoneType'>
<type 'NoneType'>
<type 'cv2.cv.iplimage'>
<type 'NoneType'>
<type 'NoneType'>
<type 'cv2.cv.iplimage'>
<type 'NoneType'>
有人知道问题来自哪里?
Does anybody know where the problem comes from ?
谢谢
编辑:
我注意到我的相机开启需要几秒钟,所以我在进入while之前放了一些延迟。对于noneType问题,我不知道为什么我得到一个正确的图像每3帧。甚至我只是固定它通过检查,如果我们得到一个正确的图像的条件,这里是代码:
I noticed it takes some seconds before my camera turn on, so I put some delay before entering the "while". As for the noneType problem I have no idea why I get a correct image every 3 frames..anyway I just "fixed" it by putting a condition that checks if we get a correct image, here is the code:
import cv
cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE)
camera_index = 0
capture = cv.CaptureFromCAM(camera_index)
c = cv.WaitKey(5000)
def repeat():
global capture #declare as globals since we are assigning to them now
global camera_index
frame = cv.QueryFrame(capture)
if frame:
cv.ShowImage("w1", frame)
c = cv.WaitKey(10)
while True:
repeat()
推荐答案
建议如下:
- camera_index = -1
-
放置第一帧,以防
- camera_index = -1
drop first frame just in case
firstImage = copy.deepcopy(cv.QueryFrame(capture))
firstImage = copy.deepcopy(cv.QueryFrame(capture))
分享我的代码供您参考:
Share my code for your reference:
import cv2 as cv
import copy
camera_index = -1
capture = cv.CaptureFromCAM(camera_index)
isRunning = True
firstImage = copy.deepcopy(cv.QueryFrame(capture)) #drop first frame which might empty
cv.NamedWindow("Webcam", cv.CV_WINDOW_AUTOSIZE);
def repeat():
global capture #declare as globals since we are assigning to them now
global camera_index
global isRunning
global firstImage
currImage = cv.QueryFrame(capture)
cv.ShowImage("Webcam",currImage)
c = cv.WaitKey(10)
if(c==27):
isRunning = False
if (c!=-1):
print str(c)
while isRunning:
repeat()
这篇关于OpenCV Python:QueryFrame返回None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!