Read Video Streams with cv2.VideoCapture

Tutorial

You can use the cv2.VideoCapture method to connect to a webcam and read frames from the webcam.

The cv2.VideoCapture method accepts the ID of the webcam to which you want to connect. Your default camera -- for example, your system webcam -- should have the ID 0. Other cameras will increment from there.


import cv2 as cv

cap = cv.VideoCapture(0)

while True:
    ret, frame = cap.read()

    if not ret:
        break

    cv.imshow('frame', frame)

    if cv.waitKey(1) == ord('q'):
        break

cap.release()
cv.destroyAllWindows()

Next Steps

OpenCV can be used with the open source supervision Python package.

supervision provides an extensive range of functionalities for working with computer vision models. With supervision, you can:

1. Process and filter detections and segmentation masks from a range of popular models (YOLOv5, Ultralytics YOLOv8, MMDetection, and more).
2. Process and filter classifications.
3. Compute confusion matrices.

And more! To learn about the full range of functionality in supervision, check out the supervision documentation.