vehicle-entry-exit-logging / openvino_sample.py
vagheshpatel's picture
Update native RC1 samples and supported device documentation
87df721 verified
Raw History Blame Contribute Delete
3.77 kB
# SPDX-License-Identifier: MIT
# Copyright (C) Intel Corporation
#
# Vehicle Entry/Exit Logging: OpenVINO Runtime sample.
# See README.md for prerequisites and inputs. Run: python3 openvino_sample.py
import cv2
import numpy as np
import openvino as ov
VEHICLE_CLASS_IDS = {2: "car"}
CONF_THRESHOLD = 0.4
# Select the model: "yolo26n" (default) or "detr-resnet-50".
MODEL = "yolo26n"
INPUT_SIZE = 800 if MODEL.startswith("detr") else 640
LINE_RATIO = 0.6
MAX_DIST = 80
core = ov.Core()
model = core.read_model(f"{MODEL}_openvino_model/{MODEL}.xml")
# Change device to "GPU" or "NPU" to run on integrated GPU or NPU.
compiled = core.compile_model(model, "CPU")
cap = cv2.VideoCapture("smart_parking_720p_30fps.mp4")
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))
line_y = int(height * LINE_RATIO)
def fmt_time(seconds: float) -> str:
"""Format elapsed video time as MM:SS.mmm."""
minutes, secs = divmod(seconds, 60)
return f"{int(minutes):02d}:{secs:06.3f}"
writer = cv2.VideoWriter(
"output_openvino.mp4", cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height))
tracks: dict[int, tuple[int, int]] = {}
entry_time: dict[int, float] = {}
next_id = 0
entered = 0
exited = 0
frame_idx = 0
while True:
ok, frame = cap.read()
if not ok:
break
frame_idx += 1
h0, w0 = frame.shape[:2]
sx, sy = w0 / INPUT_SIZE, h0 / INPUT_SIZE
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, ...]
output = compiled([blob])[compiled.output(0)][0]
mask = (output[:, 4] >= CONF_THRESHOLD) & np.isin(
output[:, 5].astype(int), list(VEHICLE_CLASS_IDS.keys()))
dets = output[mask]
centroids = []
for det in dets:
cx = int(((det[0] + det[2]) / 2) * sx)
cy = int(((det[1] + det[3]) / 2) * sy)
centroids.append((cx, cy))
new_tracks: dict[int, tuple[int, int]] = {}
used = set()
for tid, (px, py) in tracks.items():
best_d = MAX_DIST
best_j = -1
for j, (cx, cy) in enumerate(centroids):
if j in used:
continue
d = abs(cx - px) + abs(cy - py)
if d < best_d:
best_d = d
best_j = j
if best_j >= 0:
cx, cy = centroids[best_j]
used.add(best_j)
t = frame_idx / fps
if py < line_y <= cy:
exited += 1
enter_t = entry_time.pop(tid, None)
if enter_t is not None:
print(
f"EXIT track={tid:<3} entry={fmt_time(enter_t)} "
f"exit={fmt_time(t)}", flush=True)
else:
print(f"EXIT track={tid:<3} exit={fmt_time(t)}", flush=True)
elif py >= line_y > cy:
entered += 1
entry_time[tid] = t
print(f"ENTRY track={tid:<3} entry={fmt_time(t)}", flush=True)
new_tracks[tid] = (cx, cy)
for j, (cx, cy) in enumerate(centroids):
if j not in used:
new_tracks[next_id] = (cx, cy)
next_id += 1
tracks = new_tracks
for det in dets:
x1 = int(det[0] * sx)
y1 = int(det[1] * sy)
x2 = int(det[2] * sx)
y2 = int(det[3] * sy)
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(frame, "car", (x1, max(y1 - 6, 0)),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
writer.write(frame)
cap.release()
writer.release()
print(f"Total: entered={entered} exited={exited}", flush=True)