Motion Detection
Motion detection finds areas of the video frame where significant change has occurred between frames. It is the foundation of security cameras, activity monitoring, and event-triggered recording.
10 min•By Priygop Team•Updated 2026
Frame Difference Motion Detection
Frame Difference Motion Detection
import cv2
import numpy as np
def frame_difference_motion(video_source=0, threshold=30, min_area=500):
"""
Detect motion by comparing consecutive frames.
Highlights regions where pixels changed significantly.
"""
cap = cv2.VideoCapture(video_source)
if not cap.isOpened():
print("Could not open video source")
return
ret, prev_frame = cap.read()
if not ret:
return
prev_gray = cv2.cvtColor(prev_frame, cv2.COLOR_BGR2GRAY)
prev_gray = cv2.GaussianBlur(prev_gray, (21, 21), 0)
frame_count = 0
motion_events = 0
while frame_count < 500: # Process 500 frames
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21, 21), 0)
# Absolute difference between current and previous frame
diff = cv2.absdiff(prev_gray, gray)
# Threshold the difference image
_, motion_mask = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)
# Clean up mask
motion_mask = cv2.dilate(motion_mask, None, iterations=2)
# Find motion contours
contours, _ = cv2.findContours(
motion_mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
)
motion_detected = False
result = frame.copy()
for contour in contours:
if cv2.contourArea(contour) < min_area:
continue
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(result, (x, y), (x+w, y+h), (0, 255, 0), 2)
motion_detected = True
if motion_detected:
motion_events += 1
cv2.putText(result, "MOTION DETECTED", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 3)
prev_gray = gray
frame_count += 1
cap.release()
print(f"Processed {frame_count} frames, motion events: {motion_events}")
frame_difference_motion(video_source="security_camera.mp4")Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment