Sub topic 6
Processing each frame: grayscale, blur and edges
This chapter assumes you can already run the read loop from the previous chapters (ok, frame = cap.read(), a break on failure, and a finally block that releases resources). It also assumes you are comfortable reading NumPy shapes such as (720, 1280, 3). Here you will build the usual three-step per-frame pipeline: grayscale, blur, edge detection. You will also learn what each step does to the array and where the common mistakes are.
Why this pipeline appears everywhere
Most classic vision tasks start by throwing away information that does not help. Color is often irrelevant for finding outlines or motion, and sensor noise makes pixel-level comparisons unreliable. The pipeline below reduces both.
- Grayscale collapses three channels into one, so later steps touch a third of the data.
- Gaussian blur averages each pixel with its neighbors, which suppresses noise.
- Canny edge detection marks pixels where brightness changes sharply.
Inspecting what each step returns
Before putting these calls in a loop, run them once on a single frame and print the shapes. This shows you what the loop will carry from step to step.
import cv2
cap = cv2.VideoCapture("input.mp4")
ok, frame = cap.read()
cap.release()
if not ok:
raise RuntimeError("Could not read a frame from input.mp4")
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blurred, 100, 200)
for name, img in [("frame", frame), ("gray", gray),
("blurred", blurred), ("edges", edges)]:
print(f"{name:8s} shape={img.shape} dtype={img.dtype}")For a 1280x720 file the output looks like this:
frame shape=(720, 1280, 3) dtype=uint8
gray shape=(720, 1280) dtype=uint8
blurred shape=(720, 1280) dtype=uint8
edges shape=(720, 1280) dtype=uint8The grayscale image has no channel axis at all. Its shape is (720, 1280), not (720, 1280, 1). Code that indexes img[:, :, 0] works on the color frame and raises IndexError on the gray one.
Step 1: grayscale
cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) computes a weighted sum of the channels. OpenCV uses approximately 0.299 R + 0.587 G + 0.114 B, which reflects how strongly the human eye responds to each color.
The constant must match the actual channel order. OpenCV frames are BGR, so COLOR_BGR2GRAY is correct. COLOR_RGB2GRAY would run without error but would weight red and blue the wrong way around. The result looks plausible, which makes this mistake hard to notice.
Converting an already gray image is the other common failure. In a loop, keep track of which variable holds which representation, and give each variable a name that says so (gray, edges) instead of reassigning frame.
Step 2: Gaussian blur
cv2.GaussianBlur(src, ksize, sigmaX) replaces each pixel with a weighted average of its neighborhood. The weights follow a Gaussian curve, so near pixels count more than distant ones.
ksizeis the kernel size as(width, height). Both values must be positive and odd, for example(5, 5)or(21, 21). An even size such as(4, 4)raises an error.sigmaXis the standard deviation of the curve. Passing0tells OpenCV to compute it from the kernel size, which is the usual choice.
A larger kernel removes more noise but also smears real detail. The cost grows too, since each output pixel combines more inputs.
| Kernel | Typical use | Effect |
|---|---|---|
| `(3, 3)` | Light denoising | Barely visible smoothing |
| `(5, 5)` | Before Canny | Removes sensor noise, keeps outlines |
| `(21, 21)` | Before frame differencing | Heavy smoothing, hides small flicker |
Blur matters before edge detection because Canny reacts to any sharp change in brightness. Noise creates many small, meaningless changes, and without blurring they all show up as speckle in the edge map.
Step 3: Canny edge detection
cv2.Canny(image, threshold1, threshold2) works in stages. It computes the brightness gradient at each pixel, thins the result so edges are one pixel wide, and then applies hysteresis thresholding with the two thresholds:
- A pixel with gradient above
threshold2is a strong edge and is always kept. - A pixel below
threshold1is discarded. - A pixel between the two is kept only if it connects to a strong edge.
The output is a single-channel uint8 image containing only 0 (not an edge) and 255 (edge). It is not a smoothed intensity map.
A common starting ratio is about 1:2 or 1:3 between the lower and upper threshold, so (100, 200) is a reasonable first try. Lower values give more edges and more noise. Higher values give fewer, cleaner edges and may break outlines into pieces.
Fixed thresholds fail when lighting changes during a video, because a dim scene produces weaker gradients. One widely used workaround derives the thresholds from the frame's median brightness:
import cv2
import numpy as np
def auto_canny(gray, sigma=0.33):
"""Canny with thresholds chosen around the median brightness."""
median = float(np.median(gray))
lower = int(max(0, (1.0 - sigma) * median))
upper = int(min(255, (1.0 + sigma) * median))
return cv2.Canny(gray, lower, upper)This is a heuristic, not a guarantee. It adapts to overall brightness but not to contrast, so check the result on your own footage.
Putting the steps in a function
Wrap the per-frame work in a function that takes a frame and returns a result. The loop then stays short, and you can test the function on a single image without opening any video.
import cv2
import numpy as np
def process_frame(frame):
"""Return the edge map for one BGR frame."""
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
return cv2.Canny(blurred, 100, 200)
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
try:
while True:
ok, frame = cap.read()
if not ok:
break
edges = process_frame(frame)
# np.hstack needs matching shapes, so give the edge map three channels.
edges_bgr = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
side_by_side = np.hstack([frame, edges_bgr])
cv2.imshow("original | edges", side_by_side)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
finally:
cap.release()
cv2.destroyAllWindows()The COLOR_GRAY2BGR conversion copies the one gray channel into all three. It adds no color. It exists only so the arrays have the same number of dimensions. cv2.imshow accepts a single-channel image, so you do not need this step for display on its own. You need it when you combine images with np.hstack or write them with VideoWriter in its default color mode.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `error: (-215:Assertion failed) !_src.empty()` in `cvtColor` | `frame` is `None` because the read failed and the loop did not stop | Check `ok` and `break` before using `frame` |
| `Unsupported depth` or channel-count error in `cvtColor` | Converting an image that is already gray, or one that has the wrong dtype | Track which variable holds which representation |
| `ksize.width > 0 && ksize.width % 2 == 1` assertion | Even or zero kernel size | Use odd values such as `(5, 5)` |
| `ValueError: all the input array dimensions ... must match` from `np.hstack` | Stacking a 2D gray image with a 3D color frame | Convert with `COLOR_GRAY2BGR` first |
| Output video file is created but will not play | `VideoWriter` received single-channel frames, or the size differs from the size passed when it was created | Convert to BGR and keep the original `(width, height)` |
| Edge map is almost all white or all black | Thresholds far from the image's gradient range | Print `np.median(gray)` and adjust, or use `auto_canny` |
Performance and in-place changes
These three operations are fast on their own. Gaussian blur is usually the most expensive of the three, and its cost rises with kernel size and frame resolution. Two habits keep the per-frame cost down:
- Convert to gray once. Several later steps (blur, Canny, differencing) work on the same gray image. Do not call
cvtColoragain in each one. - Shrink before processing if you can. Halving the width and height with
cv2.resizeleaves a quarter of the pixels to process. This is the single largest speedup available when you do not need full resolution.
Also remember that each call allocates a new array. Assigning the result of GaussianBlur to a new name leaves the original untouched, which is usually what you want. If you draw on a frame after a processing step (rectangles, text), you change the array that other variables may still refer to. Copy with frame.copy() when you need to keep a clean version.
Measuring is better than guessing. A later chapter shows how to time each frame with time.perf_counter(). Until then, a rough test is to compare the time one process_frame call takes with the frame interval. For a 30 fps source you have about 33 ms per frame.
Summary of decisions
- Use grayscale when color does not carry the information you need. Keep the color frame if you want to display or save colored output.
- Blur before Canny and before differencing, with an odd kernel. Start at
(5, 5)for edges and increase it only if noise remains. - Choose Canny thresholds from your footage, or derive them from the median. Treat
(100, 200)as a starting point. - Convert single-channel results back to BGR only when the next step needs three channels.
Exercise
A loop calls edges = cv2.Canny(frame, 100, 200) directly on the color frame, and out.write(edges) on a VideoWriter created with the default settings. The program runs, but output.mp4 is empty or will not play. Name the two changes that would make the pipeline correct and efficient, and say what shape edges has at the point of out.write.
Show answer
First, convert the frame to grayscale (and ideally blur it) before Canny: gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY), blurred = cv2.GaussianBlur(gray, (5, 5), 0), edges = cv2.Canny(blurred, 100, 200). Second, convert the edge map back to three channels with cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR) before out.write, because the default VideoWriter expects 3-channel color frames. After Canny, edges has shape (height, width) with no channel axis and values 0 or 255. After the conversion it has shape (height, width, 3), which matches the (width, height) given to the writer.
Exercise
You change cv2.GaussianBlur(gray, (5, 5), 0) to cv2.GaussianBlur(gray, (10, 10), 0) and get an assertion error. Why, and what are two valid replacements?
Show answer
Gaussian kernel sizes must be positive and odd, so 10 is rejected. Valid replacements are (9, 9) and (11, 11). A larger odd kernel smooths more and costs more per frame.