Displaying a webcam feed using OpenCV and Python

Mitch picture Mitch · Apr 8, 2010 · Viewed 123.5k times · Source

I have been trying to create a simple program with Python which uses OpenCV to get a video feed from my webcam and display it on the screen.

I know I am partly there because the window is created and the light on my webcam flicks on, but it just doesn't seem to show anything in the window. Hopefully someone can explain what I'm doing wrong.

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

On an unrelated note, I have noticed that my webcam sometimes changes its index number in cv.CaptureFromCAM, and sometimes I need to put in 0, 1 or 2 even though I only have one camera connected and I haven't unplugged it (I know because the light doesn't come on unless I change the index). Is there a way to get Python to determine the correct index?

Answer

sastanin picture sastanin · Jul 12, 2012

An update to show how to do it in the recent versions of OpenCV:

import cv2

cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)

if vc.isOpened(): # try to get the first frame
    rval, frame = vc.read()
else:
    rval = False

while rval:
    cv2.imshow("preview", frame)
    rval, frame = vc.read()
    key = cv2.waitKey(20)
    if key == 27: # exit on ESC
        break

cv2.destroyWindow("preview")
vc.release()

It works in OpenCV-2.4.2 for me.