Sub topic 6
Processing Each Frame: Grayscale, Blur, and Edges
Prerequisites and the processing chain
This chapter assumes you know basic Python loops and try/finally, understand NumPy array shapes, and have installed opencv-python. You should also know that VideoCapture provides one image, called a frame, each time you call read().
A frame is a NumPy array. OpenCV usually stores a color frame in BGR order: blue, green, red. A typical color frame has shape (height, width, 3). Processing happens by transforming this array before displaying or saving it.
A useful pipeline is:
Each operation has a purpose:
| Stage | Input and output | Purpose |
|---|---|---|
| Grayscale | Three channels to one channel | Removes color when brightness is enough |
| Gaussian blur | One image to one smoother image | Reduces small noise and texture |
| Canny edges | Grayscale image to a binary mask | Highlights strong brightness changes |
Converting to grayscale
cv2.cvtColor changes an image from one color representation to another. For BGR-to-grayscale conversion, use cv2.COLOR_BGR2GRAY.
The result has shape (height, width), not (height, width, 1). Each pixel represents brightness. The conversion uses a weighted combination of the color channels because human vision responds differently to red, green, and blue.
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)Do not reverse the input and output arguments. cvtColor returns a new array, so assigning its result is important.
Blurring before edge detection
Real frames contain sensor noise, compression artifacts, and fine texture. Edge detection can mistake these small changes for meaningful boundaries. Gaussian blur smooths nearby pixels using a weighted neighborhood.
blurred = cv2.GaussianBlur(gray, (5, 5), 0)The kernel size (5, 5) must use positive odd numbers. Larger kernels produce stronger smoothing but can remove thin features. The final argument, 0, lets OpenCV calculate the Gaussian spread from the kernel size.
Canny edge detection looks for strong gradients, which are rapid changes in brightness. Its two thresholds control which changes become edges:
edges = cv2.Canny(blurred, 100, 200)The output is normally a single-channel image containing 0 for non-edge pixels and 255 for detected edges. Lower thresholds detect more candidates but can create extra edges. Higher thresholds produce fewer, stronger edges.
A complete read-process-display loop
The following program applies all three operations to every frame. It displays the original frame, grayscale image, blurred image, and edge image. Press q to stop.
import cv2
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
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blurred, 100, 200)
cv2.imshow("original", frame)
cv2.imshow("grayscale", gray)
cv2.imshow("blurred", blurred)
cv2.imshow("edges", edges)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
finally:
cap.release()
cv2.destroyAllWindows()waitKey(1) both processes window events and waits briefly for a key. Without it, OpenCV windows may stop updating. The finally block runs whether the file ends, the user quits, or an exception occurs.
Common mistakes include passing a color image to code that expects one channel, forgetting that OpenCV uses BGR rather than RGB, and applying Canny directly to a noisy image. Another error is using an even blur kernel such as (4, 4), which OpenCV rejects.
Exercise
Why is Gaussian blur normally applied before Canny edge detection, and what is one trade-off of increasing the blur kernel from (5, 5) to ( nine, nine )?
Show answer
Blur reduces small brightness changes that could become false edges. A larger kernel reduces more noise, but it can also remove thin real edges and make boundaries less precise.