[python] How do I access my webcam in Python?

I would like to access my webcam from Python.

I tried using the VideoCapture extension (tutorial), but that didn't work very well for me, I had to work around some problems such as it's a bit slow with resolutions >320x230, and sometimes it returns None for no apparent reason.

Is there a better way to access my webcam from Python?

This question is related to python webcam

The answer is


John Montgomery's, answer is great, but at least on Windows, it is missing the line

vc.release()

before

cv2.destroyWindow("preview")

Without it, the camera resource is locked, and can not be captured again before the python console is killed.


gstreamer can handle webcam input. If I remeber well, there are python bindings for it!


import cv2 as cv

capture = cv.VideoCapture(0)

while True:
    isTrue,frame = capture.read()
    cv.imshow('Video',frame)
    if cv.waitKey(20) & 0xFF==ord('d'):
        break

capture.release()
cv.destroyAllWindows()

0 <-- refers to the camera , replace it with file path to read a video file

cv.waitKey(20) & 0xFF==ord('d') <-- to destroy window when key is pressed