Webcam stream and OpenCV - python

18,083

Solution 1

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

Solution 2

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()
Share:
18,083
Edgar Andrés Margffoy Tuay
Author by

Edgar Andrés Margffoy Tuay

Systems and Computing Engineering student at Uniandes. Currently interested on Computer Vision, Neural Networks and general purpose Scientific Computing, also I'm a Python enthusiast with motivation to learn new things and programming languages, besides, I also like to implement new programming languages and Compilers.

Updated on July 28, 2022

Comments

  • Edgar Andrés Margffoy Tuay
    Edgar Andrés Margffoy Tuay almost 2 years

    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.