Views
No views yet
| Property | Value |
|---|---|
| Category | Object Detection (Crowd Density + Movement) |
| Base Model | YOLO26 (Ultralytics) |
| Source Framework | PyTorch (Ultralytics) |
| Supported Precisions | FP32, FP16, INT8 (mixed-precision) |
| Inference Engine | OpenVINO |
| Hardware | CPU, GPU, NPU |
| Detected Class | person (COCO class 0) |
LOW / MEDIUM / HIGH), and
tracks each person across frames to estimate the dominant flow direction of the
crowd.
It is built on YOLO26, a
state-of-the-art real-time object detector trained on the COCO dataset, exported
to OpenVINO IR and filtered at runtime to the person class.yolo26n, yolo26s, yolo26m, yolo26l, yolo26x.
Smaller variants (yolo26n, yolo26s) are recommended for high-FPS edge
deployment; larger variants improve recall in dense crowds.Density levels are defined by two count thresholds (defaults:LOWfor fewer than 10 people,MEDIUMfor 10-25,HIGHfor more than 25). Tune these to the field of view and expected occupancy of your deployment site.
1python3 -m venv .venv --system-site-packages
2source .venv/bin/activateNote: The--system-site-packagesflag is required so the virtual environment can access the system-installed OpenVINO and DLStreamer Python packages.
1chmod +x export_and_quantize.sh
2./export_and_quantize.sh1./export_and_quantize.sh yolo26n FP32 # full-precision
2./export_and_quantize.sh yolo26n INT8 # quantized
3./export_and_quantize.sh yolo26s # larger variant, default FP16yolo26n with any variant (yolo26s, yolo26m, yolo26l, yolo26x).
The second argument selects the precision (FP32, FP16, INT8); the default is FP16.openvino, ultralytics; adds nncf for INT8).test.jpg) and a sample test video (test_video.mp4).yolo26n_openvino_model/ -- FP32 or FP16 OpenVINO IR model directory.yolo26n_crowdanalysis_int8.xml / yolo26n_crowdanalysis_int8.bin -- INT8 quantized model (only when INT8 is selected).| Precision | CPU | GPU | NPU |
|---|---|---|---|
| FP32 | Yes | Yes | No |
| FP16 | Yes | Yes | Yes |
| INT8 | Yes | Yes | Yes |
Note: The INT8 calibration uses the bundled sample image. For production accuracy, replace it with a representative set of frames from the target deployment site.
person class, reports the crowd count and density level per frame, tracks each
person with a lightweight IoU tracker to estimate the dominant flow direction,
and writes the annotated result to output_openvino.mp4.
Change the device string to run on CPU, GPU, or NPU.1import cv2
2import numpy as np
3import openvino as ov
4
5PERSON_CLASS_ID = 0
6CONF_THRESHOLD = 0.4
7INPUT_SIZE = 640
8
9# Crowd-density thresholds (person count per frame).
10DENSITY_LOW_MAX = 10 # fewer than 10 -> LOW
11DENSITY_MEDIUM_MAX = 25 # 10-25 -> MEDIUM, more than 25 -> HIGH
12
13# Movement tracking.
14IOU_MATCH_THRESHOLD = 0.3
15MAX_MISSED_FRAMES = 15
16
17
18def density_level(count):
19 if count < DENSITY_LOW_MAX:
20 return "LOW", (0, 200, 0)
21 if count <= DENSITY_MEDIUM_MAX:
22 return "MEDIUM", (0, 200, 255)
23 return "HIGH", (0, 0, 255)
24
25
26def iou(box_a, box_b):
27 ax1, ay1, ax2, ay2 = box_a
28 bx1, by1, bx2, by2 = box_b
29 ix1, iy1 = max(ax1, bx1), max(ay1, by1)
30 ix2, iy2 = min(ax2, bx2), min(ay2, by2)
31 inter = max(0, ix2 - ix1) * max(0, iy2 - iy1)
32 if inter == 0:
33 return 0.0
34 area_a = max(0, ax2 - ax1) * max(0, ay2 - ay1)
35 area_b = max(0, bx2 - bx1) * max(0, by2 - by1)
36 return inter / float(area_a + area_b - inter)
37
38
39class CentroidTracker:
40 """Minimal IoU tracker that records each track's last centroid so we can
41 estimate per-frame movement (flow) vectors."""
42
43 def __init__(self):
44 self._next_id = 1
45 self._tracks = {} # id -> {"box", "centroid", "missed"}
46
47 def update(self, boxes):
48 unmatched = set(self._tracks)
49 assignments, moves = [], []
50 for box in boxes:
51 cx = (box[0] + box[2]) / 2.0
52 cy = (box[1] + box[3]) / 2.0
53 best_id, best_iou = None, IOU_MATCH_THRESHOLD
54 for tid in unmatched:
55 score = iou(box, self._tracks[tid]["box"])
56 if score > best_iou:
57 best_id, best_iou = tid, score
58 if best_id is not None:
59 tid = best_id
60 unmatched.discard(tid)
61 pcx, pcy = self._tracks[tid]["centroid"]
62 moves.append((cx - pcx, cy - pcy))
63 else:
64 tid = self._next_id
65 self._next_id += 1
66 self._tracks[tid] = {"box": box, "centroid": (cx, cy), "missed": 0}
67 assignments.append((box, tid))
68 for tid in unmatched:
69 self._tracks[tid]["missed"] += 1
70 if self._tracks[tid]["missed"] > MAX_MISSED_FRAMES:
71 del self._tracks[tid]
72 return assignments, moves
73
74
75core = ov.Core()
76model = core.read_model("yolo26n_openvino_model/yolo26n.xml")
77compiled = core.compile_model(model, "CPU") # or "GPU", "NPU"
78
79cap = cv2.VideoCapture("test_video.mp4")
80fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
81width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
82height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
83writer = cv2.VideoWriter(
84 "output_openvino.mp4", cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height))
85
86tracker = CentroidTracker()
87
88while True:
89 ok, frame = cap.read()
90 if not ok:
91 break
92 h0, w0 = frame.shape[:2]
93 sx, sy = w0 / INPUT_SIZE, h0 / INPUT_SIZE
94
95 blob = cv2.resize(frame, (INPUT_SIZE, INPUT_SIZE))
96 blob = cv2.cvtColor(blob, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
97 blob = blob.transpose(2, 0, 1)[np.newaxis, ...] # NCHW
98
99 # YOLO26 end-to-end output: [1, 300, 6] = [x1, y1, x2, y2, confidence, class_id]
100 output = compiled([blob])[compiled.output(0)][0]
101 mask = (output[:, 4] >= CONF_THRESHOLD) & (output[:, 5].astype(int) == PERSON_CLASS_ID)
102 dets = output[mask]
103
104 boxes = [(d[0] * sx, d[1] * sy, d[2] * sx, d[3] * sy) for d in dets]
105 assignments, moves = tracker.update(boxes)
106
107 for box, _tid in assignments:
108 x1, y1, x2, y2 = (int(v) for v in box)
109 cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
110
111 count = len(boxes)
112 level, color = density_level(count)
113 cv2.putText(frame, f"Crowd: {count} ({level})", (10, 40),
114 cv2.FONT_HERSHEY_SIMPLEX, 1.0, color, 2)
115
116 # Movement: mean of all per-track displacements -> dominant flow arrow.
117 if moves:
118 mdx = float(np.mean([m[0] for m in moves]))
119 mdy = float(np.mean([m[1] for m in moves]))
120 ox, oy = width // 2, height - 40
121 cv2.arrowedLine(frame, (ox, oy),
122 (int(ox + mdx * 10), int(oy + mdy * 10)),
123 (255, 0, 0), 3, tipLength=0.3)
124 cv2.putText(frame, f"Flow dx={mdx:+.1f} dy={mdy:+.1f}", (10, 75),
125 cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0), 2)
126
127 writer.write(frame)
128
129cap.release()
130writer.release()
131print("Saved: output_openvino.mp4")export_and_quantize.sh script downloads test_video.mp4 automatically.
Run the OpenVINO sample above.
It reads test_video.mp4, prints the crowd count and density level per frame,
and writes the annotated video to output_openvino.mp4 with a green box around
each detected person, the Crowd: N (LEVEL) overlay, and a blue arrow showing
the dominant crowd flow.Tip: For production testing, replace the bundledtest_video.mp4with footage from your target deployment site and re-tune the density thresholds.

gvadetect, assigns a stable track ID to each person with gvatrack, filters
detections to the person class in a buffer probe using the GStreamer Analytics
metadata API (GstAnalytics), overlays bounding boxes, and saves the annotated
result to output_dlstreamer.mp4. The probe prints the crowd count, density
level, and dominant flow direction per frame.Notes on running this sample:
Use the FP16 IR (yolo26n_openvino_model/yolo26n.xml). On DLStreamer 2026.0.0,gvadetectcannot auto-derive a YOLO post-processor from the INT8 model produced by the bundled script. To use the INT8 model, supply a matchingmodel-procJSON. Class names are read automatically from the model's embeddedmetadata.yamlby DLStreamer 2026.0+ -- no externallabels-fileis required. Filtering withobject-class=persondirectly ongvadetectis rejected wheninference-regionisfull-frame(the default), so the sample filters by detection label in the buffer probe instead. ExportPYTHONPATHso the DLStreamer Python module is importable:bash1source /opt/intel/openvino_2026/setupvars.sh 2source /opt/intel/dlstreamer/scripts/setup_dls_env.sh 3export PYTHONPATH=/opt/intel/dlstreamer/python:\ 4/opt/intel/dlstreamer/gstreamer/lib/python3/dist-packages:${PYTHONPATH:-}
1import gi
2
3gi.require_version("Gst", "1.0")
4gi.require_version("GstAnalytics", "1.0")
5from gi.repository import Gst, GLib, GstAnalytics
6
7Gst.init([])
8
9INPUT_VIDEO = "test_video.mp4"
10
11# Crowd-density thresholds (person count per frame).
12DENSITY_LOW_MAX = 10 # fewer than 10 -> LOW
13DENSITY_MEDIUM_MAX = 25 # 10-25 -> MEDIUM, more than 25 -> HIGH
14
15
16def density_level(count):
17 if count < DENSITY_LOW_MAX:
18 return "LOW"
19 if count <= DENSITY_MEDIUM_MAX:
20 return "MEDIUM"
21 return "HIGH"
22
23
24# For CPU: change device=GPU to device=CPU.
25# For NPU: change device=GPU to device=NPU (batch-size=1, nireq=4 recommended).
26pipeline_str = (
27 f"filesrc location={INPUT_VIDEO} ! decodebin3 ! "
28 "videoconvert ! "
29 "gvadetect model=yolo26n_openvino_model/yolo26n.xml "
30 "device=GPU "
31 "threshold=0.4 ! queue ! "
32 "gvatrack tracking-type=zero-term-imageless ! queue ! "
33 "gvawatermark displ-cfg=show-roi=person ! "
34 "videoconvert ! video/x-raw,format=I420 ! "
35 "openh264enc ! h264parse ! "
36 "mp4mux ! filesink name=sink location=output_dlstreamer.mp4"
37)
38pipeline = Gst.parse_launch(pipeline_str)
39
40sink = pipeline.get_by_name("sink")
41sink_pad = sink.get_static_pad("sink")
42
43prev_centroid = {} # track_id -> (cx, cy)
44
45
46def on_buffer(pad, info):
47 buf = info.get_buffer()
48 rmeta = GstAnalytics.buffer_get_analytics_relation_meta(buf)
49 if rmeta is None:
50 return Gst.PadProbeReturn.OK
51
52 # OD and tracking metadata share one id space and can be interleaved
53 # (id=1 -> ODMtd, id=2 -> TrackingMtd, ...), so scan every id and stop only
54 # after several consecutive misses.
55 ods, tracks = [], []
56 idx, misses = 1, 0
57 while misses < 20:
58 ok_od, od = rmeta.get_od_mtd(idx)
59 ok_trk, trk = rmeta.get_tracking_mtd(idx)
60 if ok_od:
61 ods.append(od)
62 misses = 0
63 elif ok_trk:
64 tracks.append(trk)
65 misses = 0
66 else:
67 misses += 1
68 idx += 1
69
70 count, moves = 0, []
71 for od in ods:
72 if GLib.quark_to_string(od.get_obj_type()) != "person":
73 continue
74 count += 1
75 _, x, y, w, h, _ = od.get_location()
76 cx, cy = x + w / 2.0, y + h / 2.0
77 for trk in tracks:
78 if rmeta.get_relation(od.id, trk.id) == GstAnalytics.RelTypes.NONE:
79 continue
80 ok_trk, track_id, _, _, _ = trk.get_info()
81 if not ok_trk:
82 continue
83 if track_id in prev_centroid:
84 pcx, pcy = prev_centroid[track_id]
85 moves.append((cx - pcx, cy - pcy))
86 prev_centroid[track_id] = (cx, cy)
87 break
88
89 if count:
90 level = density_level(count)
91 if moves:
92 mdx = sum(m[0] for m in moves) / len(moves)
93 mdy = sum(m[1] for m in moves) / len(moves)
94 print(f"Crowd: {count} ({level}) flow dx={mdx:+.1f} dy={mdy:+.1f}",
95 flush=True)
96 else:
97 print(f"Crowd: {count} ({level})", flush=True)
98 return Gst.PadProbeReturn.OK
99
100
101sink_pad.add_probe(Gst.PadProbeType.BUFFER, on_buffer)
102
103pipeline.set_state(Gst.State.PLAYING)
104bus = pipeline.get_bus()
105bus.timed_pop_filtered(
106 Gst.CLOCK_TIME_NONE,
107 Gst.MessageType.EOS | Gst.MessageType.ERROR,
108)
109pipeline.set_state(Gst.State.NULL)
device=GPU -- default in the sample code.device=CPU -- change device=GPU to device=CPU.device=NPU -- change device=GPU to device=NPU; use batch-size=1 and nireq=4 for best NPU utilization.