Sub topic 13
Putting it together: simple motion detection by frame differencing
This chapter combines the read loop, per-frame processing, and timing into one working program. The program detects motion by comparing each frame with the one before it.
You should already be comfortable with these points from earlier chapters:
- Opening a source with
cv2.VideoCaptureand checkingisOpened(). - Running a read loop that stops when
cap.read()returnsFalse. - Converting a BGR frame to grayscale and blurring it.
- Releasing resources in a
finallyblock. - Basic NumPy shapes and dtypes.
The idea behind frame differencing
Frame differencing assumes that a still scene produces nearly identical consecutive frames. When something moves, the pixels it covers or uncovers change value. Subtract one frame from the next and the changed pixels stand out.
The method has four steps:
- Convert the frame to grayscale, so each pixel is one number.
- Blur it, so sensor noise does not look like motion.
- Take the absolute difference from the previous processed frame.
- Threshold the difference into a mask, then count or inspect the changed pixels.
A first working version
The following program reads a file, compares each frame with the previous one, and prints the number of changed pixels along with the time spent on that frame.
import time
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
ok, prev = cap.read()
if not ok:
raise RuntimeError("No frames in input.mp4")
prev = cv2.GaussianBlur(cv2.cvtColor(prev, cv2.COLOR_BGR2GRAY), (21, 21), 0)
try:
while True:
start = time.perf_counter()
ok, frame = cap.read()
if not ok:
break
gray = cv2.GaussianBlur(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY), (21, 21), 0)
diff = cv2.absdiff(prev, gray)
_, mask = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)
moving = cv2.countNonZero(mask)
prev = gray
elapsed_ms = (time.perf_counter() - start) * 1000
print(f"changed pixels: {moving}, frame time: {elapsed_ms:.1f} ms")
finally:
cap.release()Reading the code step by step
The program reads one frame before the loop. That frame has no predecessor, so it only serves as the first reference. It would be wrong to compute a difference on it.
Inside the loop, cv2.absdiff(prev, gray) computes |prev - gray| for every pixel. This function matters because ordinary subtraction on uint8 arrays wraps around. For example, 10 - 20 in unsigned 8-bit arithmetic gives 246, not -10. absdiff avoids that problem and gives the true magnitude of the change.
cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY) returns two values. The first is the threshold value used, which this program ignores with _. The second is the mask, in which every pixel above 25 becomes 255 and every other pixel becomes 0.
cv2.countNonZero(mask) counts the white pixels. That count is a rough measure of how much of the image changed.
The last step in the loop sets prev = gray. The reference frame moves forward each iteration, so the program always compares neighbouring frames.
Why the blur matters
Camera sensors produce small random variations in every frame, even for a perfectly still scene. Compression adds more variation. Without a blur, many pixels cross the threshold by chance, and the count is never near zero.
A Gaussian blur averages each pixel with its neighbours, which smooths out isolated noise. The kernel size (21, 21) is large. A larger kernel suppresses more noise but also smears small moving objects. Kernel sizes must be odd.
| Setting | Effect when increased | Risk when too high | Risk when too low |
|---|---|---|---|
| Blur kernel size | Less noise in the difference | Small or thin objects disappear | Noise triggers false motion |
| Threshold value | Fewer pixels count as changed | Slow or low-contrast motion is missed | Noise and lighting flicker count as motion |
| Pixel count to declare motion | Fewer false alarms | Small moving objects are ignored | Single noisy blobs trigger alerts |
Tune these three values together on footage that resembles your real use case. There is no universal setting.
Turning a count into a decision
A raw pixel count is a signal, not a decision. To decide "motion happened", compare the count with a minimum area. The minimum should scale with the frame size, so express it as a fraction of the total number of pixels.
import cv2
MIN_CHANGED_FRACTION = 0.01 # 1% of the frame must change
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
ok, prev = cap.read()
if not ok:
raise RuntimeError("No frames in input.mp4")
prev = cv2.GaussianBlur(cv2.cvtColor(prev, cv2.COLOR_BGR2GRAY), (21, 21), 0)
total_pixels = prev.shape[0] * prev.shape[1]
frame_index = 0
try:
while True:
ok, frame = cap.read()
if not ok:
break
frame_index += 1
gray = cv2.GaussianBlur(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY), (21, 21), 0)
diff = cv2.absdiff(prev, gray)
_, mask = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)
fraction = cv2.countNonZero(mask) / total_pixels
if fraction >= MIN_CHANGED_FRACTION:
print(f"frame {frame_index}: motion ({fraction:.1%} changed)")
prev = gray
finally:
cap.release()The frame index starts at 1 because the first frame was consumed before the loop. It then counts the frames that have been compared.
Showing where the motion is
A count says that something moved, but not where. The mask is itself an image, so you can display it or find the outlines of the changed regions.
Two extra steps make the mask more useful. Dilation grows the white regions so that fragments of one object join together. cv2.findContours then returns the outline of each connected region.
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
ok, prev = cap.read()
if not ok:
raise RuntimeError("No frames in input.mp4")
prev = cv2.GaussianBlur(cv2.cvtColor(prev, cv2.COLOR_BGR2GRAY), (21, 21), 0)
try:
while True:
ok, frame = cap.read()
if not ok:
break
gray = cv2.GaussianBlur(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY), (21, 21), 0)
diff = cv2.absdiff(prev, gray)
_, mask = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)
mask = cv2.dilate(mask, None, iterations=2)
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
if cv2.contourArea(contour) < 500:
continue # ignore small blobs
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow("motion", frame)
prev = gray
if cv2.waitKey(1) & 0xFF == ord("q"):
break
finally:
cap.release()
cv2.destroyAllWindows()In this version, cv2.findContours returns two values: the contours and a hierarchy. This holds for OpenCV 4. Older OpenCV 3 releases returned three values, so code copied from old tutorials can fail with an unpacking error.
The colour (0, 255, 0) is green because OpenCV uses BGR order. The rectangle is drawn on the original colour frame, not on the grayscale image, so it appears in colour.
Limits and failure modes
Frame differencing is simple and fast, and it has known weaknesses.
- Lighting changes. A cloud passing over a window, or a camera adjusting its exposure, changes many pixels at once. The method reports this as motion.
- Slow movement. If an object moves only a pixel or two per frame, the difference between neighbouring frames is small and may fall under the threshold. Comparing against a frame from several steps earlier helps, at the cost of detecting an object twice (once where it was, once where it is).
- Uniform objects. The inside of a large, evenly coloured moving object does not change, so only its leading and trailing edges appear in the mask. Dilation partly fills these gaps.
- Ghost outlines. The difference shows both where the object is now and where it was in the previous frame.
- Camera shake. A moving camera makes the whole image change. The method assumes a fixed camera.
- Frame rate dependence. At a higher frame rate, an object moves less between frames, so the same threshold behaves differently. Re-tune when the source changes.
For harder scenes, a background model that learns the static scene over time handles gradual lighting changes better. OpenCV provides such models in cv2.createBackgroundSubtractorMOG2. Frame differencing remains a good first tool because you can understand every step.
Keeping up with a live camera
Timing matters most when the source is a camera. A file is read as fast as your code asks for frames, so a slow loop only takes longer. A camera produces frames at a fixed rate. If your processing takes longer than one frame interval, the pipeline falls behind.
For a 30 fps camera, the interval is about 33 ms. The program in the first example prints the frame time, so you can compare it with this budget directly.
| Camera rate | Time budget per frame |
|---|---|
| 15 fps | about 66.7 ms |
| 30 fps | about 33.3 ms |
| 60 fps | about 16.7 ms |
When the loop exceeds the budget, what happens depends on the driver and backend. Some backends buffer frames, so you read older and older frames and the delay grows. Others drop frames. In both cases the result is not real-time.
You have several options to reduce the cost per frame:
- Downscale the frame with
cv2.resizebefore the blur. Motion detection rarely needs full resolution. - Use a smaller blur kernel, since blur cost grows with kernel size.
- Process only every second or third frame.
- Avoid drawing and display work in the loop when running unattended.
Downscaling is usually the best first step. Halving both width and height cuts the pixel count to a quarter.
Common mistakes
- Forgetting to seed
prevbefore the loop, which causes aNameErroror a comparison withNone. - Updating
prevwith the raw frame instead of the blurred grayscale frame. The shapes and dtypes then differ, andabsdiffraises an error or gives meaningless results. - Using plain subtraction (
prev - gray) onuint8arrays, which wraps around. - Using a pixel-count threshold that is fixed in absolute terms, so it breaks when the resolution changes.
- Ignoring the return value of
cv2.thresholdand mixing up the two outputs. - Calling
cv2.waitKeynever or with a long delay, so the window does not refresh or the loop runs slowly.
Exercise
A motion detector works on a 640x480 test video but reports motion constantly on a 1920x1080 camera, using a fixed threshold of 3000 changed pixels. Give two likely causes and one fix for each.
Show answer
First, the fixed pixel count is too small for the larger frame. 1920x1080 has about 6.75 times as many pixels as 640x480, so noise alone can exceed 3000 pixels. Fix: use a fraction of total pixels, such as 1%. Second, the blur kernel that suppressed noise at 640x480 covers a much smaller part of the scene at 1920x1080, so noise survives. Fix: downscale the frame to a smaller size before blurring, or enlarge the kernel. Lighting flicker or camera auto-exposure is also a valid second cause, fixed by raising the threshold or fixing the exposure.
Exercise
Why does cv2.absdiff(prev, gray) give a correct result when prev - gray on two uint8 arrays does not? What would you see in the output?
Show answer
NumPy uint8 subtraction wraps modulo 256, so a pixel that got darker, for example 10 minus 20, becomes 246, a very large value. In the mask, darkening areas would look like strong changes with the wrong magnitude, and small decreases would look like large changes. absdiff computes the absolute value of the difference without wraparound, so a change of 10 in either direction gives 10.
Exercise
A camera runs at 30 fps and your loop measures 45 ms per frame. Describe what happens and name two changes that would fix it.
Show answer
The budget is about 33 ms, so the loop is slower than the camera. Depending on the backend, frames queue up and you see increasing delay, or frames are dropped. Two fixes: downscale each frame before processing, and process only every second frame. Reducing the blur kernel or removing display and drawing work also helps.