Webcam stream and OpenCV - python


Question

I want to get the video stream from my webcam using python and OpenCV, for that task i've implemented this simple code:

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.

1
8
6/13/2012 6:24:49 PM

Accepted Answer

You need to add waitkey function at end.

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. 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()
22
6/13/2012 7:32:04 PM

Below code works for python 2.7 and opencv that has build for python 2.7

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()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon