Sub topic 7
Reading and setting capture properties
This chapter assumes you can write the basic cap.read() loop from the earlier chapters. You should also know that a frame is a NumPy array with shape (height, width, channels). Everything here uses the opencv-python package.
What a capture property is
A cv2.VideoCapture object holds metadata about its source: frame size, frame rate, the current position, the codec, and for cameras things like exposure and brightness. You access this metadata through two methods:
cap.get(prop_id)returns the property value as a Pythonfloat.cap.set(prop_id, value)requests a new value and returns abool.
Property IDs are integer constants such as cv2.CAP_PROP_FPS. All values are floats, even for things that are naturally integers, so you usually wrap width, height, and frame counts in int(...).
The most common properties are:
| Constant | Meaning | Typical use |
|---|---|---|
| `CAP_PROP_FRAME_WIDTH` | Frame width in pixels | Size a `VideoWriter` |
| `CAP_PROP_FRAME_HEIGHT` | Frame height in pixels | Size a `VideoWriter` |
| `CAP_PROP_FPS` | Frames per second | Writer rate, duration math |
| `CAP_PROP_FRAME_COUNT` | Total frames in a file | Progress display |
| `CAP_PROP_POS_FRAMES` | 0-based index of the next frame to be read | Seeking |
| `CAP_PROP_POS_MSEC` | Timestamp of the current position in milliseconds | Timestamps |
| `CAP_PROP_FOURCC` | Four-character codec code, packed in a number | Inspecting or choosing a format |
Which properties work depends on the backend. The backend is the library OpenCV uses to talk to the source, such as FFmpeg for files or V4L2 on Linux and Media Foundation on Windows for cameras. A property that one backend supports may be ignored by another.
Reading properties from a file
The following script opens a file and prints the main properties. It also decodes the FourCC value, which comes back as a float holding four packed bytes.
import cv2
def fourcc_to_str(value):
code = int(value)
return "".join(chr((code >> (8 * i)) & 0xFF) for i in range(4))
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
try:
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
codec = fourcc_to_str(cap.get(cv2.CAP_PROP_FOURCC))
print(f"size: {width}x{height}")
print(f"fps: {fps:.3f}")
print(f"frames: {total}")
print(f"codec: {codec!r}")
if fps > 0 and total > 0:
print(f"length: about {total / fps:.1f} seconds")
finally:
cap.release()The duration line divides the frame count by the frame rate. It guards against zero because, as the next section shows, either value can be unusable.
When a property is not what it seems
get never raises an exception. When it cannot answer, it returns a value such as 0.0 or -1.0. Treat every property as a hint to validate, not as a guarantee.
- Unsupported property. You get
0.0. You cannot distinguish "the value is zero" from "this backend does not know", so zero is a signal to fall back to a default. - FPS of 0. Many webcams and some network streams report no frame rate. The earlier chapter used
cap.get(cv2.CAP_PROP_FPS) or 30.0. Theorworks because0.0is falsy. - Wrong or missing frame count. Container formats that do not store a frame count, and live streams, report
0, a negative number, or a rough estimate. UseCAP_PROP_FRAME_COUNTfor a progress bar, never as a loop bound. Loop untilread()fails. - Variable frame rate. Some files change their frame rate over time. The reported FPS is then an average, and
total / fpsis only approximate. - Size before the first frame. Some backends fill in the width and height only after the first successful read. If you see
0x0right after opening, read one frame and checkframe.shape.
The ground truth for frame size is the frame itself. frame.shape is (height, width, channels), with height first, which is the reverse of the order VideoWriter expects for its size argument (width, height). A mismatch between the writer size and the actual frame size is one of the most common causes of an output file that is empty or will not play, because VideoWriter.write silently drops frames of the wrong size on many backends.
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
try:
ok, frame = cap.read()
if not ok:
raise RuntimeError("No frames in input.mp4")
h, w = frame.shape[:2]
prop_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
prop_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print(f"frame array: {w}x{h}, properties: {prop_w}x{prop_h}")
if (w, h) != (prop_w, prop_h):
print("Mismatch: trust the frame array, not the properties")
finally:
cap.release()Normally the two agree. If they differ, size your writer from the array.
Orientation of phone videos
Videos recorded on phones often store frames in landscape and add a rotation flag in the metadata. Depending on your OpenCV version and backend, the frames you read may be rotated automatically or not. Recent versions provide CAP_PROP_ORIENTATION_META to read the flag and CAP_PROP_ORIENTATION_AUTO to control auto-rotation. If your output appears sideways, check these before blaming your own code, and always take the size from the frame array.
Setting properties
cap.set(prop, value) is a request. It returns True if the backend accepted the call and False otherwise. Even True does not prove the new value is in effect. A camera driver may round to the nearest mode it supports, or accept the call and ignore it. The safe pattern is to set, then read back, then use what you read.
flowchart TDThat block is not a diagram fence, so here is the real diagram.
The next function wraps this pattern. It returns the value the device actually uses.
import cv2
def request(cap, prop, value):
"""Ask for a property value and return what the device reports."""
accepted = cap.set(prop, value)
actual = cap.get(prop)
if not accepted or actual != value:
print(f"requested {value}, got {actual} (set returned {accepted})")
return actual
cap = cv2.VideoCapture(0)
if not cap.isOpened():
raise RuntimeError("Could not open camera 0")
try:
# Many cameras only deliver high resolutions or frame rates in MJPG mode,
# so ask for the codec first.
request(cap, cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*"MJPG"))
request(cap, cv2.CAP_PROP_FRAME_WIDTH, 1280)
request(cap, cv2.CAP_PROP_FRAME_HEIGHT, 720)
request(cap, cv2.CAP_PROP_FPS, 30)
ok, frame = cap.read()
if not ok:
raise RuntimeError("Camera read failed")
print("first frame shape:", frame.shape)
finally:
cap.release()Three details matter here:
- Order matters. Changing the pixel format (FourCC) can reset the resolution and frame rate, so set it first. Set width and height before FPS, because the available frame rates depend on the resolution.
- Width and height go together. Setting only the width may leave the height unchanged, and the driver then picks the nearest supported combination. Always set both.
- Comparing floats. Camera values can come back as
1280.0or as a slightly different float for properties like exposure. Comparing with!=is fine for integer-valued properties such as size. For fractional properties, compare with a tolerance.
You can only set what the source allows. On a file, setting CAP_PROP_FRAME_WIDTH does not resize the video. To change the size of file frames, use cv2.resize on each frame. For files, the property you will set most often is the position.
Position properties
CAP_PROP_POS_FRAMES is both readable and writable. Reading it tells you the 0-based index of the frame the next read() will return. After reading three frames from the start, it is 3.0. Writing it moves the read position. CAP_PROP_POS_MSEC reports the timestamp in milliseconds and can also be set. A later chapter covers seeking in detail, including the accuracy limits of compressed formats. For now, this snippet prints a timestamp beside each frame index:
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
try:
for _ in range(5):
index = int(cap.get(cv2.CAP_PROP_POS_FRAMES))
ok, frame = cap.read()
if not ok:
break
ms = cap.get(cv2.CAP_PROP_POS_MSEC)
print(f"frame {index}: position {ms:.1f} ms")
finally:
cap.release()Whether POS_MSEC refers to the frame just read or the next one depends on the backend, so use it for rough timing and not for exact synchronization. For a file with a constant frame rate, index / fps gives a dependable timestamp.
Camera-specific properties
Cameras expose controls such as CAP_PROP_BRIGHTNESS, CAP_PROP_CONTRAST, CAP_PROP_EXPOSURE, CAP_PROP_AUTOFOCUS, and CAP_PROP_AUTO_EXPOSURE. These have two problems:
- The value scales differ between backends. Exposure might be a number of seconds on one system, a power of two on another, or an arbitrary index. The auto-exposure flag also uses different magic numbers on different drivers.
- Many devices ignore them entirely.
The set-then-verify pattern is the only portable approach. If a control matters to your application, test it on the target hardware and record which backend and values worked.
Summary of rules
- Convert size and count properties with
int(...). Keep FPS as a float. - Treat
0or negative results as "unknown" and provide a fallback. - Use
frame.shapeas the final authority on frame size, and remember it is(height, width). - Use
FRAME_COUNTfor estimates only, and loop untilread()fails. - On cameras, set the FourCC first, then width and height together, then FPS, and read each back.
Exercise
A script sets cap.set(cv2.CAPPROPFRAMEWIDTH, 1920) and cap.set(cv2.CAPPROPFRAMEHEIGHT, 1080) on a webcam. Both calls return True, but the output video written with VideoWriter(..., (1920, 1080)) is empty. What is the likely cause, and how do you fix it?
Show answer
The camera probably did not switch to 1920x1080 and kept delivering a smaller mode such as 640x480. The True return values only mean the calls were accepted. VideoWriter drops frames whose size differs from the size it was created with, so nothing is written. Fix it by reading a frame first and creating the writer from frame.shape, using (frame.shape[1], frame.shape[0]) as (width, height), or by reading the properties back and handling a mismatch explicitly.
Exercise
A file reports CAPPROPFRAMECOUNT as 0 and CAPPROP_FPS as 0.0. Why is the loop "for i in range(total)" wrong here, and what should you use instead?
Show answer
With a count of 0, the loop never runs. Even when the count is nonzero, it can be an estimate that does not match the number of decodable frames. Use "while True" with "ok, frame = cap.read()" and break when ok is False. For the frame rate, fall back to a default such as 30.0 when the reported FPS is 0.