简体   繁体   English

网络摄像头流和OpenCV - python

[英]Webcam stream and OpenCV - python

I want to get the video stream from my webcam using python and OpenCV, for that task i've implemented this simple code: 我想使用python和OpenCV从我的网络摄像头获取视频流,为此任务我实现了这个简单的代码:

import cv

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

def repeat():
  frame = cv.QueryFrame(capture)
  cv.ShowImage("w1", frame)


while True:
  repeat()

when i try to execute it, i get the following error: 当我尝试执行它时,我收到以下错误:

andfoy@ubuntu:~/Python$ python camera.py
VIDIOC_QUERYMENU: Argumento inválido   
VIDIOC_QUERYMENU: Argumento inválido
VIDIOC_QUERYMENU: Argumento inválido

I changed the following line as suggested by other posts: 我按照其他帖子的建议更改了以下行:

capture = cv.CaptureFromCAM(0)

to: 至:

capture = cv.CaptureFromCAM(-1) 

but the error persists. 但错误仍然存​​在。

You need to add waitkey function at end. 你需要在最后添加waitkey函数。

Below piece of code works fine for me. 下面的代码对我来说很好。

import cv
cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE)
capture = cv.CaptureFromCAM(0)

def repeat():
    frame = cv.QueryFrame(capture)
    cv.ShowImage("w1", frame)

while True:
    repeat()
    if cv.WaitKey(33)==27:
        break

cv.DestroyAllWindows()

And if you are not aware, Present OpenCV uses new python api cv2 and it has lots of features. 如果你不知道,现在的OpenCV使用新的python api cv2 ,它有很多功能。 In that, same code is written as : 在那,相同的代码写为:

import cv2
import numpy as np
c = cv2.VideoCapture(0)

while(1):
    _,f = c.read()
    cv2.imshow('e2',f)
    if cv2.waitKey(5)==27:
        break
cv2.destroyAllWindows()

Below code works for python 2.7 and opencv that has build for python 2.7 下面的代码适用于为Python 2.7构建的python 2.7和opencv

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

if not(cap.isOpened()):
    cap.open()

while(cap.isOpened()):
    ret, frame = cap.read()
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM