person-detection / openvino_sample.py
vagheshpatel's picture
Update native RC1 samples and supported device documentation
8af681b verified
Raw History Blame Contribute Delete
1.59 kB
# SPDX-License-Identifier: MIT
# Copyright (C) Intel Corporation
#
# Person detection with YOLO26 or DETR using OpenVINO Runtime.
# Run: python3 openvino_sample.py (expects test.jpg and the exported model).
import cv2
import numpy as np
import openvino as ov
# Select the model: "yolo26n" (default) or "detr-resnet-50".
MODEL = "yolo26n"
PERSON_CLASS_ID = 0
CONF_THRESHOLD = 0.4
INPUT_SIZE = 800 if MODEL.startswith("detr") else 640
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")
image = cv2.imread("test.jpg")
h0, w0 = image.shape[:2]
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)
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
person_count = len(dets)
print(f"Detected persons: {person_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"Persons: {person_count}", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0), 2,
)
cv2.imwrite("output_openvino.jpg", image)