Download opencv_sample.py from Intel/motion-detection: direct link, hf CLI and curl.
- Browser
- Download file 1.94 kB
-
https://huggingface.co/Intel/motion-detection/resolve/main/opencv_sample.py
- Command line
-
hf download hf://Intel/motion-detection/opencv_sample.py
-
curl -L -o opencv_sample.py https://huggingface.co/Intel/motion-detection/resolve/main/opencv_sample.py
1.94 kB
| # SPDX-License-Identifier: MIT | |
| # Copyright (C) Intel Corporation | |
| # | |
| # Motion Detection: OpenCV sample. | |
| # See README.md for prerequisites and inputs. Run: python3 opencv_sample.py | |
| import cv2 | |
| import numpy as np | |
| INPUT_VIDEO = "test_video.mp4" | |
| MIN_AREA = 500 # ignore motion blobs smaller than this many pixels | |
| cap = cv2.VideoCapture(INPUT_VIDEO) | |
| fps = cap.get(cv2.CAP_PROP_FPS) or 30.0 | |
| width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) | |
| height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) | |
| bg = cv2.createBackgroundSubtractorMOG2( | |
| history=200, varThreshold=25, detectShadows=True) | |
| writer = cv2.VideoWriter( | |
| "output_opencv.mp4", cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height)) | |
| kernel = np.ones((3, 3), np.uint8) | |
| frame_idx = 0 | |
| motion_frames = 0 | |
| while True: | |
| ok, frame = cap.read() | |
| if not ok: | |
| break | |
| frame_idx += 1 | |
| fg = bg.apply(frame) | |
| # MOG2 marks shadows as 127; keep only strong foreground (255). | |
| fg = cv2.threshold(fg, 200, 255, cv2.THRESH_BINARY)[1] | |
| fg = cv2.morphologyEx(fg, cv2.MORPH_OPEN, kernel) | |
| contours, _ = cv2.findContours( | |
| fg, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) | |
| regions = [c for c in contours if cv2.contourArea(c) >= MIN_AREA] | |
| if regions: | |
| motion_frames += 1 | |
| for c in regions: | |
| x, y, w, h = cv2.boundingRect(c) | |
| cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2) | |
| status_text = "Motion Detected" if regions else "No Motion" | |
| status_color = (0, 0, 255) if regions else (0, 255, 0) | |
| cv2.putText(frame, status_text, (10, 30), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.9, status_color, 2) | |
| cv2.putText(frame, f"Motion regions: {len(regions)}", (10, 60), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2) | |
| print(f"Frame {frame_idx}: motion regions={len(regions)}", flush=True) | |
| writer.write(frame) | |
| cap.release() | |
| writer.release() | |
| print(f"Motion detected in {motion_frames} frames", flush=True) | |