Sub topic 3
Opening a file or a camera with VideoCapture
This chapter assumes you know basic Python, including try/finally. It also assumes you can read NumPy shapes and have opencv-python installed. You should know that a video is a sequence of images played at a frame rate. Here you learn how to turn a file path, a camera index, or a stream URL into an object you can read frames from. You also learn how to tell reliably whether that worked.
What VideoCapture is
cv2.VideoCapture is the class OpenCV uses to read frames. One object wraps a source and a backend. The source is where frames come from. The backend is the library that decodes or captures them, such as FFmpeg for files or V4L2 for cameras on Linux. Your code stays the same for every source. You construct the object, check that it opened, and then call read() repeatedly. The next chapter covers that read loop.
The constructor accepts three kinds of source:
| Source | Example | Typical backend |
|---|---|---|
| Video file path (a string) | `"input.mp4"` | FFmpeg or GStreamer |
| Device index (an integer) | `0` | V4L2 on Linux, DirectShow or Media Foundation on Windows, AVFoundation on macOS |
| Stream URL or pipeline string | `"rtsp://host/stream"` | FFmpeg or GStreamer |
The constructor does not raise on failure
Most Python libraries raise an exception when a file is missing. VideoCapture does not. If the path is wrong, the codec is unsupported, or the camera is busy, the constructor still returns an object. That object is simply not open. The first sign of trouble is usually a later read() returning False, which is easy to mistake for the end of a file.
Always check isOpened() immediately after construction:
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
print("Opened successfully")
cap.release()Raising an exception at this point puts the error next to its cause. Without the check, you might see a blank window, an empty output file, or a NoneType error several lines later.
Opening a video file
Pass the path as a string. The path is resolved relative to the current working directory, which is where you launched Python, not where your script lives. This is the most common reason a file fails to open when it clearly exists. When in doubt, build an absolute path from the script's location:
from pathlib import Path
import cv2
video_path = Path(__file__).resolve().parent / "input.mp4"
print("Looking for:", video_path, "exists:", video_path.exists())
cap = cv2.VideoCapture(str(video_path))
if not cap.isOpened():
raise RuntimeError(f"Could not open {video_path}")
cap.release()Older OpenCV versions did not accept Path objects directly, so convert with str().
A file can exist and still fail to open. The usual reasons are:
- The container or codec is not supported by the FFmpeg build inside your OpenCV wheel. Some proprietary codecs are missing from pip wheels.
- The file is truncated or corrupt, so the header cannot be parsed.
- The path contains characters that the backend handles badly. This has historically been a problem for non-ASCII paths on Windows.
To find out whether the file itself is the problem, try playing it in another tool, or re-encode it with ffmpeg -i input.mov -c:v libx264 output.mp4.
Opening a camera
For a camera, pass an integer index. Index 0 is normally the first device the operating system lists, 1 the second, and so on. The numbering is not stable across machines. Plugging in a USB webcam, or a virtual camera from conferencing software, can change which index is which.
import cv2
cap = cv2.VideoCapture(0)
if not cap.isOpened():
raise RuntimeError("Could not open camera 0")
ok, frame = cap.read()
print("First read ok:", ok, "shape:", None if not ok else frame.shape)
cap.release()A camera that opens can still fail on its first read. On macOS, the terminal or editor needs camera permission in the system settings. Another application that holds the camera can also make the open or the read fail. This is why the camera example in this tutorial reads a frame immediately and handles a failed read, as well as checking isOpened().
Finding which index is your camera
There is no portable call that lists cameras. A common workaround is to probe a small range of indexes:
import cv2
for index in range(5):
cap = cv2.VideoCapture(index)
if cap.isOpened():
ok, frame = cap.read()
if ok:
h, w = frame.shape[:2]
print(f"Camera {index}: {w}x{h}")
else:
print(f"Camera {index}: opened but could not read")
cap.release()Expect warnings printed by the backend for the indexes that do not exist. That is normal. Probing is slow on some systems because every failed index waits for a timeout, so keep the range small and do not run it inside your main loop.
Choosing a backend
OpenCV picks a backend automatically, but you can request one with the second argument, apiPreference. This matters when the default choice misbehaves. For example, on Windows the Media Foundation backend can take many seconds to open some cameras, while DirectShow opens them quickly.
import cv2
# Windows: try DirectShow instead of the default Media Foundation
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
if not cap.isOpened():
raise RuntimeError("Could not open camera 0 with DirectShow")
print("Backend in use:", cap.getBackendName())
cap.release()Common constants include cv2.CAP_ANY (automatic, the default), cv2.CAP_FFMPEG, cv2.CAP_GSTREAMER, cv2.CAP_V4L2, cv2.CAP_DSHOW, cv2.CAP_MSMF, and cv2.CAP_AVFOUNDATION. A constant is only useful if your OpenCV build includes that backend. Requesting one that is missing makes the open fail, so isOpened() returns False.
getBackendName() reports which backend is actually in use. Printing it is a quick way to confirm what OpenCV chose when you debug a source that behaves differently on two machines.
Network streams
A string that starts with a protocol such as rtsp:// or http:// opens a network stream through FFmpeg or GStreamer:
import cv2
url = "rtsp://user:[email protected]:554/stream1"
cap = cv2.VideoCapture(url, cv2.CAP_FFMPEG)
if not cap.isOpened():
raise RuntimeError("Could not open the stream")
cap.release()Streams behave like cameras in one respect: they have no end of file, and a read can fail at any time because of a network problem. They also differ from files. Opening can block for several seconds while the connection is made. Do not put credentials in source files you commit. Read them from environment variables instead.
Opening later with open()
You can create an empty capture and open it afterwards. The open() method takes the same arguments as the constructor and returns a boolean:
import cv2
cap = cv2.VideoCapture()
print("Before open:", cap.isOpened())
if cap.open("input.mp4"):
print("Opened")
else:
print("Failed to open")
cap.release()This form is useful when you reuse one object to try several sources in turn, such as falling back from a camera to a sample file. Calling open() on an already open capture releases the old source first.
A reusable opening helper
Repeating the same check in every script invites mistakes. A small helper keeps the behavior consistent and gives clear messages:
import os
import cv2
def open_capture(source, backend=cv2.CAP_ANY):
"""Open a file, camera index or URL, or raise a clear error."""
if isinstance(source, str) and "://" not in source:
if not os.path.isfile(source):
raise FileNotFoundError(f"No such video file: {source}")
cap = cv2.VideoCapture(source, backend)
if not cap.isOpened():
cap.release()
raise RuntimeError(f"OpenCV could not open source {source!r}")
return cap
cap = open_capture("input.mp4")
try:
print("Opened with backend:", cap.getBackendName())
finally:
cap.release()The helper separates two failures that isOpened() alone cannot tell apart. A missing file raises FileNotFoundError. A file that exists but cannot be decoded raises RuntimeError. It also calls release() before raising, so a failed open does not leave a half-initialized object behind.
The decision at the start of every program
Common mistakes
| Symptom | Likely cause | What to do |
|---|---|---|
| `isOpened()` is `False` for a file that exists | Relative path resolved from the wrong directory, or an unsupported codec | Print the absolute path and check it exists. Test the file in another player. |
| The first `read()` returns `False` and no error appears | The `isOpened()` check was skipped | Check right after construction. |
| Camera index `0` opens the wrong device | A virtual or secondary camera took index `0` | Probe indexes and print the frame size for each. |
| Camera opens on Linux but frames are black or the read fails | Another process holds the device, or permissions are missing | Close other applications. Check that your user can access `/dev/video0`. |
| Opening a camera takes many seconds on Windows | The Media Foundation backend is slow for that device | Try `cv2.CAP_DSHOW`. |
| `cv2.VideoCapture(Path(...))` raises a `TypeError` | An older OpenCV does not accept `Path` objects | Pass `str(path)`. |
Closing the capture
Every successfully opened capture holds a file handle or a device. Call release() when you finish, ideally in a finally block as the helper example does. For a camera this matters because the device stays locked until the process exits or you release it, and other programs cannot use it in the meantime. A later chapter covers cleanup and failure handling in full.
Summary
VideoCaptureaccepts a file path, a device index, or a URL. The rest of your code does not need to know which.- The constructor never raises. Check
isOpened()straight away and raise your own error. - Relative paths depend on the working directory. Camera indexes depend on the machine.
- The optional backend argument lets you override the automatic choice, and
getBackendName()shows what was used. - Release the capture even when something fails.
Exercise
A script calls cap = cv2.VideoCapture("clips/walk.mp4") and goes straight into a loop that calls cap.read(). The file is in the right folder, but the loop ends at once and the output video is empty. Name two possible causes, and say what single addition to the script would make the failure obvious.
Show answer
Possible causes: the path is relative and Python was launched from a different directory, so the file is not found; or the file exists but uses a codec that this OpenCV build cannot decode. In both cases VideoCapture does not raise an error. The first read() returns False and the loop exits without a message. Adding an if not cap.isOpened(): raise RuntimeError(...) check right after the constructor makes the failure visible. Printing the absolute path helps tell the two causes apart.
Exercise
You write a probing loop that opens camera indexes 0 to 4 and prints the frame size for each. Index 0 prints "opened but could not read" on your laptop, and index 1 prints 1280x720. What does this tell you, and which index should your program use?
Show answer
Index 0 opened, so the device exists, but no frame could be read. A virtual camera, a device held by another application, or a missing permission could cause this. Index 1 delivered a real frame, so it is the usable camera. Use index 1 on this machine, and make the index a command-line argument or setting, because the numbering can differ on other machines.