Files
2025-05-22 16:47:31 +02:00

70 lines
2.3 KiB
Python

import cv2
import numpy as np
# --- Setup ---
video_path = "recordings/San Francisco/TV314 -- I-280 At Indiana St/20250307/202503070633299140970800.mkv" # or 0 for webcam
cap = cv2.VideoCapture(video_path)
# Background subtractor
bg_subtractor = cv2.createBackgroundSubtractorMOG2(history=500, varThreshold=50, detectShadows=False)
# Read first frame to initialize
ret, frame_prev = cap.read()
gray_prev = cv2.cvtColor(frame_prev, cv2.COLOR_BGR2GRAY)
# Motion accumulator for temporal smoothing
motion_accumulator = np.zeros_like(gray_prev, dtype=np.uint16)
while True:
ret, frame = cap.read()
if not ret:
break
# --- Background subtraction ---
fg_mask = bg_subtractor.apply(frame)
fg_mask = cv2.morphologyEx(fg_mask, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
# --- Optical flow computation ---
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
flow = cv2.calcOpticalFlowFarneback(
gray_prev, gray, None,
pyr_scale=0.5, levels=3, winsize=15,
iterations=3, poly_n=5, poly_sigma=1.2, flags=0
)
gray_prev = gray.copy()
magnitude, _ = cv2.cartToPolar(flow[..., 0], flow[..., 1])
motion_mask = (magnitude > 1.0).astype(np.uint8) * 255
# --- Combine background and optical flow masks ---
combined_mask = cv2.bitwise_and(fg_mask, motion_mask)
# --- Update motion accumulator (temporal smoothing) ---
motion_accumulator = cv2.add(motion_accumulator, combined_mask.astype(np.uint16))
motion_accumulator = cv2.subtract(motion_accumulator, 1) # decay by 1
motion_accumulator = np.clip(motion_accumulator, 0, 255)
motion_stable = (motion_accumulator > 20).astype(np.uint8) * 255
# --- Filter by contour area ---
contours, _ = cv2.findContours(motion_stable, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
final_mask = np.zeros_like(motion_stable)
for cnt in contours:
area = cv2.contourArea(cnt)
if 500 < area < 50000:
cv2.drawContours(final_mask, [cnt], -1, 255, -1)
# --- Visualization ---
output = frame.copy()
output[final_mask == 255] = [0, 255, 0] # highlight moving areas in green
cv2.imshow("Detected Motion", output)
cv2.imshow("Final Mask", final_mask)
key = cv2.waitKey(30)
if key == 27: # ESC to quit
break
cap.release()
cv2.destroyAllWindows()