File size: 1,943 Bytes
85d519e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# 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)