Sub topic 2
A frame is a NumPy array (and OpenCV uses BGR)
Every frame that cap.read() returns is a NumPy array. Once you know its shape, dtype and channel order, you can slice, copy and combine frames with ordinary NumPy code. This chapter covers what that array looks like, how its memory behaves, and the mistakes that follow from OpenCV's blue-green-red channel order.
Prerequisites
This chapter assumes you have these skills:
- Basic Python: functions, loops,
try/finally. - NumPy basics:
shape,dtype, indexing and slicing. opencv-pythonandnumpyinstalled.- A video is a sequence of still images shown at a frame rate. The first chapter covered this.
What `cap.read()` hands you
A successful cap.read() returns a pair: a boolean flag and an array. With a normal color file or camera, the array has three dimensions and the uint8 data type.
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
ok, frame = cap.read()
cap.release()
if not ok:
raise RuntimeError("No frame could be read")
print(type(frame)) # <class 'numpy.ndarray'>
print(frame.shape) # for example (1080, 1920, 3)
print(frame.dtype) # uint8
print(frame.ndim, frame.size) # 3 and 1080 * 1920 * 3
print(frame.flags["C_CONTIGUOUS"]) # TrueEach part of the result matters:
shapeis(height, width, channels). Rows come first, so the height comes before the width.dtypeisuint8. Every value is an integer from 0 to 255.- The array is C-contiguous. Rows are stored one after another in memory, and the three values of each pixel sit next to each other.
If ok is False, frame is None. Calling frame.shape on it raises AttributeError. This is why the read loop checks the flag before touching the frame.
Common array layouts
Frames change layout as you process them. This table lists the ones you will meet most often.
| Layout | Shape | dtype | Where it comes from |
|---|---|---|---|
| Color frame | `(H, W, 3)` | `uint8` | `cap.read()` on most sources |
| Grayscale | `(H, W)` | `uint8` | `cv2.cvtColor(..., COLOR_BGR2GRAY)`, `cv2.Canny` output |
| Color with alpha | `(H, W, 4)` | `uint8` | Some PNG images, `COLOR_BGR2BGRA` |
| Normalized float | `(H, W, 3)` | `float32` | `frame.astype(np.float32) / 255.0` |
A grayscale image has no channel axis at all. Code that assumes frame.shape[2] exists will crash on it.
BGR, not RGB
OpenCV stores the channels of a color image in the order blue, green, red. This is a historical convention in the library. It is not a property of video files. Almost everything else orders channels as red, green, blue, including Matplotlib, Pillow and most deep learning frameworks.
For one pixel, frame[y, x] gives [B, G, R]. You can check this without any video file by building a frame yourself.
import cv2
import numpy as np
frame = np.zeros((120, 160, 3), dtype=np.uint8)
frame[:] = (255, 0, 0) # B=255, G=0, R=0: pure blue
print(frame[10, 10]) # [255 0 0]
b, g, r = cv2.split(frame)
print(b[10, 10], g[10, 10], r[10, 10]) # 255 0 0
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
print(rgb[10, 10]) # [ 0 0 255]
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
print(gray.shape, gray[10, 10]) # (120, 160) 29The grayscale value of pure blue is 29, not 255. The conversion weights the channels by how bright the eye perceives each one: roughly 0.299 R + 0.587 G + 0.114 B. Blue contributes little.
Display functions in OpenCV, such as cv2.imshow, cv2.imwrite and VideoWriter.write, all expect BGR. A mismatch shows up as swapped colors. Skin looks blue, and the sky looks orange.
Reversing channels with a slice
frame[:, :, ::-1] also reverses the channel order, and many tutorials use it. It does not copy data. It creates a view with a negative stride on the last axis.
import cv2
import numpy as np
frame = np.zeros((120, 160, 3), dtype=np.uint8)
frame[:] = (255, 0, 0)
view = frame[:, :, ::-1]
print(view[0, 0]) # [ 0 0 255]
print(view.flags["C_CONTIGUOUS"]) # False
rgb = np.ascontiguousarray(view)
print(rgb.flags["C_CONTIGUOUS"]) # True
cv2.rectangle(rgb, (10, 10), (50, 50), (0, 255, 0), 2)Some OpenCV functions that draw on or modify an array in place reject non-contiguous input. The error message mentions that the layout of the array is incompatible. np.ascontiguousarray or cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) produces a proper contiguous copy. For frames, cvtColor is the clearer choice.
Indexing: rows first, and views
Because the array is indexed [row, column], a pixel at horizontal position x and vertical position y is frame[y, x]. OpenCV drawing functions use the opposite order. cv2.circle(img, (x, y), ...) takes x first. Likewise, cv2.resize(frame, (new_width, new_height)) and VideoWriter(..., (width, height)) take width first. The same frame has this relationship:
height, width = frame.shape[:2]
size_for_opencv = (width, height)If the size you pass to VideoWriter does not match the frames you write, many backends produce an empty or unplayable file without raising an error.
Slices are views
Slicing a NumPy array does not copy it. A region of interest (ROI) is a window into the original frame. Writing to the ROI changes the frame.
import cv2
import numpy as np
frame = np.zeros((120, 160, 3), dtype=np.uint8)
frame[:] = (255, 0, 0)
roi = frame[0:60, 0:80]
roi[:] = (0, 0, 255) # paint the ROI red
print(frame[0, 0]) # [ 0 0 255] frame changed too
print(frame[100, 100]) # [255 0 0] outside the ROI
patch = frame[0:60, 0:80].copy() # an independent copy
patch[:] = 0
print(frame[0, 0]) # still [ 0 0 255]
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
print(gray[0, 0], gray[100, 100]) # 76 29Use .copy() whenever you want to keep a piece of a frame while the original keeps changing. Fancy indexing with a boolean mask or an index list, such as frame[mask], already returns a copy.
Memory: frames are large
An uncompressed frame needs height × width × channels bytes. For 1920×1080 color, that is 6,220,800 bytes, about 5.9 MiB. The compressed video holds far less, because the decoder expands each frame into raw pixels.
| Resolution | Bytes per color frame | Per second at 30 fps |
|---|---|---|
| 640×480 | 921,600 (0.88 MiB) | about 26 MiB |
| 1280×720 | 2,764,800 (2.6 MiB) | about 79 MiB |
| 1920×1080 | 6,220,800 (5.9 MiB) | about 178 MiB |
Ten seconds of 1080p video held as a list of frames needs about 1.7 GiB. Process frames as they arrive and keep only what you need, such as a previous gray frame for differencing. Avoid frames.append(frame) over a whole file.
cap.read() normally allocates a fresh array on each call, so keeping a reference to an old frame is safe. If you pass your own buffer with cap.read(image=buf), the library writes into that buffer again on the next call. In that case, copy anything you want to keep.
The `uint8` trap: overflow and saturation
Because every value must fit in 0 to 255, plain NumPy arithmetic on uint8 arrays wraps around. OpenCV's arithmetic functions clamp the result at the limits instead (saturation).
import cv2
import numpy as np
a = np.full((2, 2), 200, dtype=np.uint8)
b = np.full((2, 2), 100, dtype=np.uint8)
print(a + b) # wraps: 300 - 256 = 44 in every cell
print(cv2.add(a, b)) # saturates: 255 in every cell
print(cv2.subtract(b, a)) # clamps at 0 instead of wrapping to 156Brightening a frame with frame + 50 therefore turns the brightest pixels dark. Use cv2.add, or convert to a wider type first:
import cv2
import numpy as np
frame = np.full((4, 4, 3), 220, dtype=np.uint8)
brighter = cv2.add(frame, (50, 50, 50, 0))
print(brighter[0, 0]) # [255 255 255]
as_float = frame.astype(np.float32) / 255.0
print(as_float.dtype, as_float[0, 0]) # float32 [0.8627451 0.8627451 0.8627451]The fourth value in the tuple is for an unused channel. OpenCV scalars always have four slots.
The second half of the example shows the other common fix. Convert to float32 for calculations, then scale back and cast to uint8 before displaying or writing. Many neural network preprocessing steps use this float form.
Checking assumptions in a loop
When a pipeline misbehaves, print the layout of the array at each step. A short helper makes this cheap:
import numpy as np
def describe(name, arr):
print(f"{name}: shape={arr.shape} dtype={arr.dtype} "
f"min={arr.min()} max={arr.max()} "
f"contiguous={arr.flags['C_CONTIGUOUS']}")
describe("gray", np.zeros((4, 6), dtype=np.uint8))
# gray: shape=(4, 6) dtype=uint8 min=0 max=0 contiguous=TrueCall it on the raw frame, then after each step. A shape that lost its channel axis, a dtype that became float64, or a maximum above 1.0 where you expected normalized data points straight at the faulty step.
Common errors
AttributeError: 'NoneType' object has no attribute 'shape'. A read failed and you usedframewithout checkingok.- Blue faces, orange skies. BGR data went to a library that expects RGB, or the reverse.
IndexErroror swapped width and height. You used(x, y)where NumPy needs[y, x], or(height, width)where OpenCV needs(width, height).- Edits to a copy that changed the original. You modified a slice view, and the parent frame changed as well. Use
.copy(). - Bright areas turning dark.
uint8arithmetic wrapped around. Usecv2.addor a float type. - Layout or
Materrors from OpenCV. A reversed-channel view was passed to a function that needs contiguous memory. Usecv2.cvtColorornp.ascontiguousarray.
Exercise
A frame from cap.read() has frame.shape == (480, 640, 3). What size tuple do you pass to cv2.VideoWriter for writing it, and what does frame[100, 200] return?
Show answer
Pass (640, 480), which is (width, height), the reverse of the NumPy shape order. frame[100, 200] is the pixel in row 100 (y) and column 200 (x), returned as three values in blue, green, red order.
Exercise
Why does frame + 50 produce dark spots in the brightest areas of a uint8 frame, and how do you avoid it?
Show answer
Plain NumPy addition on uint8 wraps around modulo 256, so 220 + 50 becomes 14. Use cv2.add(frame, (50, 50, 50, 0)), which saturates at 255, or convert to float32 for the calculation and clip and cast back to uint8 afterward.
Exercise
You run roi = frame[0:50, 0:50] and then roi[:] = 0. Later you notice the top-left corner of frame is black. Why, and what should you have written to keep frame unchanged?
Show answer
Basic slicing returns a view that shares memory with frame, so writing to roi writes to frame. Use roi = frame[0:50, 0:50].copy() to get an independent array.