crowd-detection / openvino_sample.py
vagheshpatel's picture
Update native RC1 samples and supported device documentation
04359c8 verified
Raw History Blame Contribute Delete
1.62 kB
# SPDX-License-Identifier: MIT
# Copyright (C) Intel Corporation
#
# Crowd Detection: 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
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
core = ov.Core()
model = core.read_model(f"{MODEL}_openvino_model/{MODEL}.xml")
compiled = core.compile_model(model, "CPU") # or "GPU", "NPU"
image = cv2.imread("test.jpg")
h0, w0 = image.shape[:2]
# Preprocess: letterbox-free resize for simplicity.
blob = cv2.resize(image, (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
# End-to-end output: [1, N, 6] = [x1, y1, x2, y2, confidence, class_id]
# (N = 300 for YOLO26, 100 for DETR)
# No NMS is needed -- YOLO26 is natively end-to-end.
output = compiled([blob])[compiled.output(0)][0]
mask = (output[:, 4] >= CONF_THRESHOLD) & (output[:, 5].astype(int) == PERSON_CLASS_ID)
dets = output[mask]
sx, sy = w0 / INPUT_SIZE, h0 / INPUT_SIZE
crowd_count = len(dets)
print(f"Detected persons: {crowd_count}")
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(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(
image, f"Crowd count: {crowd_count}", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0), 2,
)
cv2.imwrite("output_openvino.jpg", image)