Basics
Open a camera with VideoCapture
import cv2
# Default camera (index 0):
cap = cv2.VideoCapture(0)
# Check if opened successfully:
if not cap.isOpened():
raise RuntimeError("Camera not opened")
ret, frame = cap.read()
print(ret, frame.shape)
# True (480, 640, 3)
cap.release()
Camera not opening
Fix VideoCapture(0) returns False
cv2.VideoCapture(0) returns False / cap.isOpened() is False
Wrong camera index, backend issue or camera in use by another app
Try DirectShow backend: cv2.VideoCapture(0, cv2.CAP_DSHOW)Camera opens but all frames are black or have wrong size
DirectShow driver sending wrong resolution
Set resolution explicitly after openCamera works in first run then fails on second run
cap.release() not called, camera locked
Always call cap.release() in finally block- 1
Try DirectShow backend
# MSMF (default) sometimes has issues — try DirectShow:cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)print(cap.isOpened())True - 2
Set resolution explicitly
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)cap.set(cv2.CAP_PROP_FPS, 30) - 3
Try other camera indexes
# Scan available cameras:for i in range(5):cap = cv2.VideoCapture(i, cv2.CAP_DSHOW)if cap.isOpened():print(f"Camera found at index {i}")cap.release()
Backends
Windows camera backends compared
| Backend | Flag | Notes |
|---|---|---|
| MSMF (default) | cv2.CAP_MSMF | Microsoft Media Foundation. Default on Windows. Best for modern UVC cameras. |
| DirectShow | cv2.CAP_DSHOW | Older but more compatible. Try if MSMF fails. |
| Any | cv2.CAP_ANY | OpenCV picks the first working backend. |
FAQ
VideoCapture questions
Camera works in other apps but not in OpenCV
Try setting
cv2.CAP_PROP_FOURCC: cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*"MJPG")). Some cameras have better compatibility with MJPEG codec. Also check Windows Camera Privacy settings: Settings → Privacy → Camera → allow apps to access camera.VideoCapture freezes or drops frames
The camera buffer fills up if you do not read fast enough. Either reduce processing in the main loop, or run capture in a separate thread. Set
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1) to reduce buffer size.How to list all available cameras on Windows?
OpenCV has no built-in camera listing. The scan-by-index loop above is the common approach. For a proper list, use the
pygrabber library or Windows Device Manager.