How do I access my webcam in Python?

How do I access my webcam in Python?

OpenCV has support for getting data from a webcam, and it comes with Python wrappers by default, you also need to install numpy for the OpenCV Python extension (called cv2) to work.
As of 2019, you can install both of these libraries with pip:
pip install numpy
pip install opencv-python

More information on using OpenCV with Python.

An example copied from Displaying webcam feed using opencv and python:

import cv2

vc = cv2.VideoCapture(0)

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

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


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

How do I access my webcam in Python?

import cv2 as cv

capture = cv.VideoCapture(0)

while True:
    isTrue,frame =
    if cv.waitKey(20) & 0xFF==ord(d):


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

Leave a Reply

Your email address will not be published. Required fields are marked *