Sub topic 13
Putting It Together: Simple Motion Detection by Frame Differencing
Assume you know basic Python loops and try/finally, NumPy array shapes, and how OpenCV reads images. You also need opencv-python installed. This chapter combines those skills to detect motion by comparing neighboring video frames.
The working idea
A video is a sequence of images called frames. If the camera is still, most pixels in two neighboring frames have similar values. When an object moves, pixels around that object change.
Frame differencing is a simple motion-detection method:
- Read the first frame and keep it as the previous frame.
- Read the next frame.
- Convert both frames to grayscale.
- Blur them to reduce small changes caused by sensor noise.
- Calculate the absolute difference between the frames.
- Threshold the difference into a black-and-white mask.
- Count the changed pixels.
- Use that count as a motion signal.
- Make the current frame the previous frame for the next comparison.
| Operation | Result |
|---|---|
| Grayscale conversion | One intensity value per pixel |
| Gaussian blur | Fewer small, noisy changes |
| Absolute difference | Size of the change at each pixel |
| Threshold | A binary motion mask |
| Nonzero count | A simple amount-of-motion value |
The difference image is an array. A pixel value near zero means little change. A bright pixel means that the corresponding location changed. The threshold decides how large a change must be before it counts as motion.
A complete file example
The following program processes input.mp4. It displays the original frame and the binary motion mask. Press q to stop. The first frame is only used to create the initial baseline, so the program starts detecting motion with the second frame.
import time
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
ok, previous = cap.read()
if not ok:
cap.release()
raise RuntimeError("The video contains no readable frames")
previous_gray = cv2.cvtColor(previous, cv2.COLOR_BGR2GRAY)
previous_gray = cv2.GaussianBlur(previous_gray, (21, 21), 0)
try:
while True:
start = time.perf_counter()
ok, frame = cap.read()
if not ok:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21, 21), 0)
difference = cv2.absdiff(previous_gray, gray)
_, motion_mask = cv2.threshold(
difference, 25, 255, cv2.THRESH_BINARY
)
changed_pixels = cv2.countNonZero(motion_mask)
total_pixels = motion_mask.shape[0] * motion_mask.shape[1]
motion_ratio = changed_pixels / total_pixels
elapsed_ms = (time.perf_counter() - start) * 1000
print(
f"changed pixels: {changed_pixels}, "
f"motion ratio: {motion_ratio:.3f}, "
f"processing time: {elapsed_ms:.1f} ms"
)
cv2.imshow("video", frame)
cv2.imshow("motion mask", motion_mask)
previous_gray = gray
if cv2.waitKey(1) & 0xFF == ord("q"):
break
finally:
cap.release()
cv2.destroyAllWindows()cv2.absdiff computes the absolute value of the difference for each pixel. This avoids treating a change from dark to light differently from a change from light to dark.
cv2.threshold changes every difference value into either zero or 255. In this example, a difference greater than 25 becomes white. countNonZero then counts the white pixels.
You can turn the motion ratio into a decision:
if motion_ratio > 0.02:
print("Motion detected")The value 0.02 means that more than two percent of the image must differ. This is a starting point, not a universal setting.
Common errors and tuning
A small blur kernel can leave too much sensor noise. A large kernel can erase small moving objects. The kernel dimensions must be positive odd numbers, such as (5, 5) or (21, 21).
The threshold has a similar trade-off. A low threshold detects subtle changes but creates false positives. A high threshold ignores noise but can miss slow or dim motion.
The changed-pixel count also depends on image size. A ratio is easier to compare across videos than a raw count. For a camera, test several scenes and choose a threshold based on observed values.
When using a live camera, there is no end-of-file. A failed read call still must stop the loop because it can indicate a disconnected camera or another capture failure.
Exercise
Why does the program blur both the previous frame and the current frame before calling absdiff?
Show answer
Blurring reduces small pixel changes caused by sensor noise and compression. Applying it to both frames keeps the comparison consistent.