Motion detection and background subtraction are key techniques in video surveillance, traffic monitoring, and activity recognition. OpenCV provides background subtractors that help identify moving objects from video streams.
A simple method is comparing consecutive frames to detect changes.
import cv2
cap = cv2.VideoCapture("video.mp4")
ret, frame1 = cap.read()
ret, frame2 = cap.read()
while cap.isOpened():
diff = cv2.absdiff(frame1, frame2)
gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
_, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)
dilated = cv2.dilate(thresh, None, iterations=3)
contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
if cv2.contourArea(c) < 500:
continue
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(frame1, (x,y), (x+w,y+h), (0,255,0), 2)
cv2.imshow("Motion Detection", frame1)
frame1 = frame2
ret, frame2 = cap.read()
if not ret or cv2.waitKey(40) == 27: # ESC to quit
break
cap.release()
cv2.destroyAllWindows()
OpenCV provides BackgroundSubtractorMOG2 and KNN to separate foreground (moving objects) from background.
cap = cv2.VideoCapture("video.mp4")
fgbg = cv2.createBackgroundSubtractorMOG2()
while True:
ret, frame = cap.read()
if not ret:
break
fgmask = fgbg.apply(frame)
cv2.imshow("Original", frame)
cv2.imshow("Foreground Mask", fgmask)
if cv2.waitKey(30) & 0xFF == 27: # ESC key
break
cap.release()
cv2.destroyAllWindows()
✅ In this lesson, you learned how to implement motion detection using frame differencing
and background subtraction using MOG2.
These techniques are widely used in real-time surveillance, robotics, and monitoring systems.
👉 Next, we will study Object Tracking (Meanshift & Camshift).
