File size: 4,773 Bytes
953285e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# SPDX-License-Identifier: MIT
# Copyright (C) Intel Corporation
#
# Running Detection: OpenVINO Runtime sample.
# See README.md for prerequisites and inputs. Run: python3 openvino_sample.py

import subprocess

import cv2
import numpy as np
import openvino as ov

PERSON_CLASS_ID = 0
CONF_THRESHOLD = 0.4
# Select the model: "yolo26n" (default) or "detr-resnet-50".
MODEL = "yolo26n"
INPUT_SIZE = 800 if MODEL.startswith("detr") else 640
RUNNING_SPEED = 250.0   # pixels/second
MIN_RUN_FRAMES = 3      # sustained frames above the threshold before flagging
MAX_MATCH_DIST = 120    # max center distance (px) to link a track across frames
ALERT_HOLD_SECONDS = 2.0  # latch the alert banner to keep it from flickering

# Change DEVICE to "GPU" or "NPU" to run on integrated GPU or NPU.
DEVICE = "CPU"
INPUT_VIDEO = "running.mp4"

core = ov.Core()
model = core.read_model(f"{MODEL}_openvino_model/{MODEL}.xml")
compiled = core.compile_model(model, DEVICE)
output_port = compiled.output(0)

cap = cv2.VideoCapture(INPUT_VIDEO)
fps = cap.get(cv2.CAP_PROP_FPS) or 25.0
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
ALERT_HOLD_FRAMES = max(1, int(ALERT_HOLD_SECONDS * fps))

proc = subprocess.Popen(
    ["ffmpeg", "-y", "-f", "rawvideo", "-pix_fmt", "bgr24",
     "-s", f"{width}x{height}", "-r", str(fps),
     "-i", "pipe:0", "-c:v", "libx264", "-pix_fmt", "yuv420p",
     "-movflags", "+faststart", "output_openvino.mp4"],
    stdin=subprocess.PIPE, stderr=subprocess.DEVNULL,
)

tracks: dict[int, dict] = {}   # id -> {cx, cy, run_frames}
next_id = 0
flagged: set[int] = set()
alert_hold = 0
frame_idx = 0

while True:
    ok, frame = cap.read()
    if not ok:
        break
    frame_idx += 1
    dt = 1.0 / fps

    blob = cv2.resize(frame, (INPUT_SIZE, INPUT_SIZE))
    blob = cv2.cvtColor(blob, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
    blob = blob.transpose(2, 0, 1)[np.newaxis, ...]  # NCHW

    output = compiled([blob])[output_port][0]
    mask = (output[:, 4] >= CONF_THRESHOLD) & (output[:, 5].astype(int) == PERSON_CLASS_ID)
    dets = output[mask]

    sx, sy = width / INPUT_SIZE, height / INPUT_SIZE
    detections = []
    for det in dets:
        x1, y1 = int(det[0] * sx), int(det[1] * sy)
        x2, y2 = int(det[2] * sx), int(det[3] * sy)
        detections.append((x1, y1, x2, y2, (x1 + x2) // 2, (y1 + y2) // 2))

    # Greedy nearest-center association to the previous frame's tracks.
    used = set()
    assignments = {}
    for i, (_, _, _, _, cx, cy) in enumerate(detections):
        best_id, best_dist = None, MAX_MATCH_DIST
        for tid, tr in tracks.items():
            if tid in used:
                continue
            d = np.hypot(cx - tr["cx"], cy - tr["cy"])
            if d < best_dist:
                best_id, best_dist = tid, d
        if best_id is None:
            best_id = next_id
            next_id += 1
            tracks[best_id] = {"cx": cx, "cy": cy, "run_frames": 0}
        used.add(best_id)
        assignments[i] = best_id

    new_tracks = {}
    frame_running = False
    for i, (x1, y1, x2, y2, cx, cy) in enumerate(detections):
        tid = assignments[i]
        prev = tracks.get(tid, {"cx": cx, "cy": cy, "run_frames": 0})
        speed = np.hypot(cx - prev["cx"], cy - prev["cy"]) / dt
        run_frames = prev["run_frames"] + 1 if speed >= RUNNING_SPEED else 0
        new_tracks[tid] = {"cx": cx, "cy": cy, "run_frames": run_frames}

        is_running = run_frames >= MIN_RUN_FRAMES
        frame_running = frame_running or is_running
        color = (0, 0, 255) if is_running else (0, 255, 0)
        cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
        label = f"RUNNING {int(speed)}px/s" if is_running else f"{int(speed)}px/s"
        cv2.putText(frame, label, (x1, max(y1 - 8, 12)),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
        if is_running and tid not in flagged:
            flagged.add(tid)
            print(f"RUNNING id={tid} speed={int(speed)}px/s frame={frame_idx}", flush=True)

    tracks = new_tracks

    # Latch the alert so the banner reflects a sustained state, not a single
    # transient frame: once running is seen it stays on for ALERT_HOLD_FRAMES.
    alert_hold = ALERT_HOLD_FRAMES if frame_running else max(0, alert_hold - 1)
    alert_on = alert_hold > 0
    banner = "RUNNING DETECTED" if alert_on else "NO RUNNING DETECTED"
    banner_color = (0, 0, 255) if alert_on else (0, 180, 0)
    cv2.rectangle(frame, (0, 0), (width, 40), (0, 0, 0), -1)
    cv2.putText(frame, banner, (10, 28),
                cv2.FONT_HERSHEY_SIMPLEX, 0.9, banner_color, 2)

    proc.stdin.write(frame.tobytes())

cap.release()
proc.stdin.close()
proc.wait()
print("Wrote output_openvino.mp4", flush=True)