vagheshpatel commited on
Commit
87df721
·
verified ·
1 Parent(s): 071567f

Update native RC1 samples and supported device documentation

Browse files
Files changed (5) hide show
  1. README.md +66 -16
  2. config.json +11 -3
  3. dlstreamer_sample.py +100 -0
  4. export_and_quantize.sh +119 -11
  5. openvino_sample.py +119 -0
README.md CHANGED
@@ -8,6 +8,7 @@ tags:
8
  - intel
9
  - yolo
10
  - yolo26
 
11
  - vehicle-entry-exit
12
  - tracking
13
  - short-term-imageless
@@ -24,8 +25,8 @@ language:
24
  | Property | Value |
25
  |---|---|
26
  | **Category** | Object Detection + Tracking + Line Crossing |
27
- | **Base Model** | [YOLO26](https://docs.ultralytics.com/models/yolo26/) (Ultralytics) |
28
- | **Source Framework** | PyTorch (Ultralytics) |
29
  | **Supported Precisions** | FP32, FP16, INT8 (mixed-precision) |
30
  | **Inference Engine** | OpenVINO |
31
  | **Hardware** | CPU, GPU, NPU |
@@ -53,17 +54,36 @@ Typical Metro deployments include:
53
  - **Depot and Fleet Monitoring** -- track bus/truck entry and exit from depots.
54
  - **Traffic Flow Analysis** -- measure directional flow at intersections.
55
 
56
- Available variants: `yolo26n`, `yolo26s`, `yolo26m`, `yolo26l`, `yolo26x`.
57
  Smaller variants (`yolo26n`, `yolo26s`) are recommended for high-FPS edge
58
  deployment; larger variants improve recall for distant vehicles.
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  ---
61
 
62
  ## Prerequisites
63
 
 
 
 
 
64
  - Python 3.11+
65
  - [Install OpenVINO](https://docs.openvino.ai/2026/get-started/install-openvino.html) (latest version)
66
- - [Install Intel DLStreamer](https://docs.openedgeplatform.intel.com/2026.0/edge-ai-libraries/dlstreamer/get_started/install/install_guide_ubuntu.html) (latest version)
67
 
68
  Create and activate a Python virtual environment before running the scripts:
69
 
@@ -91,22 +111,25 @@ chmod +x export_and_quantize.sh
91
 
92
  This exports the default **yolo26n** model in **FP16** precision.
93
 
94
- #### Optional: Select a Different Variant or Precision
95
 
96
  ```bash
97
- ./export_and_quantize.sh yolo26n FP32 # full-precision
98
- ./export_and_quantize.sh yolo26n INT8 # quantized
99
- ./export_and_quantize.sh yolo26s # larger variant, default FP16
 
 
100
  ```
101
 
 
102
  The script performs the following steps:
103
 
104
- 1. Installs dependencies (`openvino`, `ultralytics`; adds `nncf` for INT8).
105
  2. Downloads a sample test image (`test.jpg`) and the smart-parking sample video (`smart_parking_720p_30fps.mp4`).
106
  3. Downloads the PyTorch weights and exports to OpenVINO IR.
107
  4. *(INT8 only)* Quantizes the model using NNCF post-training quantization.
108
 
109
- Output files:
110
 
111
  - `yolo26n_openvino_model/` -- FP32 or FP16 OpenVINO IR model directory.
112
  - `yolo26n_vehicle_entry_exit_int8.xml` / `.bin` -- INT8 quantized model *(only when `INT8` is selected)*.
@@ -129,19 +152,30 @@ The saved output video shows only the car detection bounding boxes (no counter
129
  overlay or line).
130
  Change the `device` string to run on CPU, GPU, or NPU.
131
 
 
 
 
132
  ```python
 
 
 
 
 
 
133
  import cv2
134
  import numpy as np
135
  import openvino as ov
136
 
137
  VEHICLE_CLASS_IDS = {2: "car"}
138
  CONF_THRESHOLD = 0.4
139
- INPUT_SIZE = 640
 
 
140
  LINE_RATIO = 0.6
141
  MAX_DIST = 80
142
 
143
  core = ov.Core()
144
- model = core.read_model("yolo26n_openvino_model/yolo26n.xml")
145
 
146
  # Change device to "GPU" or "NPU" to run on integrated GPU or NPU.
147
  compiled = core.compile_model(model, "CPU")
@@ -242,6 +276,7 @@ cap.release()
242
  writer.release()
243
  print(f"Total: entered={entered} exited={exited}", flush=True)
244
  ```
 
245
 
246
  **Device targets:**
247
 
@@ -277,7 +312,7 @@ The annotated result is saved to `output_dlstreamer.mp4`.
277
 
278
  > **Notes on running this sample:**
279
  >
280
- > - Use the FP16 IR (`yolo26n_openvino_model/yolo26n.xml`). Class names are
281
  > read automatically from the model's embedded `metadata.yaml` by
282
  > DLStreamer 2026.0+ -- no external `labels-file` is required.
283
  > - Detections are read with the `gstgva` `VideoFrame` API
@@ -291,7 +326,16 @@ The annotated result is saved to `output_dlstreamer.mp4`.
291
  > /opt/intel/dlstreamer/gstreamer/lib/python3/dist-packages:${PYTHONPATH:-}
292
  > ```
293
 
 
 
 
294
  ```python
 
 
 
 
 
 
295
  import gi
296
 
297
  gi.require_version("Gst", "1.0")
@@ -304,12 +348,15 @@ INPUT_VIDEO = "smart_parking_720p_30fps.mp4"
304
  VEHICLE_LABELS = {"car"}
305
  LINE_RATIO = 0.6
306
 
 
 
 
307
  # For CPU: change device=GPU to device=CPU.
308
  # For NPU: change device=GPU to device=NPU (batch-size=1, nireq=4 recommended).
309
  pipeline_str = (
310
  f"filesrc location={INPUT_VIDEO} ! decodebin3 ! "
311
  "videoconvert ! "
312
- "gvadetect model=yolo26n_openvino_model/yolo26n.xml "
313
  "device=GPU "
314
  "threshold=0.4 ! queue ! "
315
  "gvatrack tracking-type=short-term-imageless ! queue ! "
@@ -384,6 +431,7 @@ bus.timed_pop_filtered(
384
  pipeline.set_state(Gst.State.NULL)
385
  print(f"Total: entered={entered} exited={exited}", flush=True)
386
  ```
 
387
 
388
  **Device targets:**
389
 
@@ -417,7 +465,9 @@ Licensed under the MIT License. See [LICENSE](LICENSE) for details.
417
  ## References
418
 
419
  - [YOLO26 Documentation](https://docs.ultralytics.com/models/yolo26/)
420
- - [Intel DLStreamer gvatrack](https://docs.openedgeplatform.intel.com/2026.0/edge-ai-libraries/dlstreamer/elements/gvatrack.html)
 
 
421
  - [BoT-SORT: Robust Multi-Object Tracking](https://arxiv.org/abs/2206.14651)
422
  - [OpenVINO Documentation](https://docs.openvino.ai/)
423
- - [Intel DLStreamer](https://docs.openedgeplatform.intel.com/2026.0/edge-ai-libraries/dlstreamer/index.html)
 
8
  - intel
9
  - yolo
10
  - yolo26
11
+ - detr
12
  - vehicle-entry-exit
13
  - tracking
14
  - short-term-imageless
 
25
  | Property | Value |
26
  |---|---|
27
  | **Category** | Object Detection + Tracking + Line Crossing |
28
+ | **Base Model** | [YOLO26](https://docs.ultralytics.com/models/yolo26/) (Ultralytics, default) or [DETR](https://huggingface.co/facebook/detr-resnet-50) (Facebook, alternative) |
29
+ | **Source Framework** | PyTorch (Ultralytics, Hugging Face Transformers) |
30
  | **Supported Precisions** | FP32, FP16, INT8 (mixed-precision) |
31
  | **Inference Engine** | OpenVINO |
32
  | **Hardware** | CPU, GPU, NPU |
 
54
  - **Depot and Fleet Monitoring** -- track bus/truck entry and exit from depots.
55
  - **Traffic Flow Analysis** -- measure directional flow at intersections.
56
 
57
+ Available variants: `yolo26n`, `yolo26s`, `yolo26m`, `yolo26l`.
58
  Smaller variants (`yolo26n`, `yolo26s`) are recommended for high-FPS edge
59
  deployment; larger variants improve recall for distant vehicles.
60
 
61
+ ### Model Selection
62
+
63
+ [DETR](https://huggingface.co/facebook/detr-resnet-50) (DEtection TRansformer) is available as an alternative to YOLO26.
64
+ DETR is a transformer-based, NMS-free detector trained on COCO and released under the Apache-2.0 license.
65
+ The export script embeds DETR normalization, box decoding, and the class remap into the OpenVINO IR, so the DETR model produces the same output layout and class ids as YOLO26.
66
+ The same OpenVINO and DLStreamer samples run either model; select one with the `MODEL` constant at the top of each sample.
67
+
68
+ | Model | Variants | Input Size | Output | License |
69
+ |---|---|---|---|---|
70
+ | YOLO26 (default) | `yolo26n`, `yolo26s`, `yolo26m`, `yolo26l` | 640 x 640 | `[1, 300, 6]` | AGPL-3.0 |
71
+ | DETR | `detr-resnet-50` | 800 x 800 | `[1, 100, 6]` | Apache-2.0 |
72
+
73
+ Choose YOLO26 for maximum throughput on edge devices.
74
+ Choose DETR when a permissively licensed transformer detector is preferred; it is heavier and runs at a lower frame rate.
75
+
76
  ---
77
 
78
  ## Prerequisites
79
 
80
+ Target stack: Intel DLStreamer **2026.3.0 RC1** with the matching OpenVINO GenAI bundle **2026.5.0.0.dev20261030** (OpenVINO Runtime **2026.5.0.dev20261030**).
81
+ Use the [native RC1 setup](../README.md#native-rc1-runtime) before running these samples; this is a development stack, not a stable release.
82
+ See the [device validation matrix](../DEVICE_SUPPORT_MATRIX.md) for measured CPU, GPU, and NPU results.
83
+
84
  - Python 3.11+
85
  - [Install OpenVINO](https://docs.openvino.ai/2026/get-started/install-openvino.html) (latest version)
86
+ - [Install Intel DLStreamer](https://docs.openedgeplatform.intel.com/dev/edge-ai-libraries/dlstreamer/get_started/install/install_guide_ubuntu.html) (latest version)
87
 
88
  Create and activate a Python virtual environment before running the scripts:
89
 
 
111
 
112
  This exports the default **yolo26n** model in **FP16** precision.
113
 
114
+ #### Optional: Select a Different Model, Variant, or Precision
115
 
116
  ```bash
117
+ ./export_and_quantize.sh yolo26n FP32 # full-precision
118
+ ./export_and_quantize.sh yolo26n INT8 # quantized
119
+ ./export_and_quantize.sh yolo26s # larger variant, default FP16
120
+ ./export_and_quantize.sh detr-resnet-50 # DETR alternative, default FP16
121
+ ./export_and_quantize.sh detr-resnet-50 INT8 # DETR quantized
122
  ```
123
 
124
+ The first argument selects the model: any YOLO26 variant (`yolo26n`, `yolo26s`, `yolo26m`, `yolo26l`) or DETR (`detr-resnet-50`).
125
  The script performs the following steps:
126
 
127
+ 1. Installs dependencies (`openvino`, `ultralytics` for YOLO26 or `transformers`, `torch` for DETR; adds `nncf` for INT8).
128
  2. Downloads a sample test image (`test.jpg`) and the smart-parking sample video (`smart_parking_720p_30fps.mp4`).
129
  3. Downloads the PyTorch weights and exports to OpenVINO IR.
130
  4. *(INT8 only)* Quantizes the model using NNCF post-training quantization.
131
 
132
+ Output files (replace `yolo26n` with the selected model, for example `detr-resnet-50`):
133
 
134
  - `yolo26n_openvino_model/` -- FP32 or FP16 OpenVINO IR model directory.
135
  - `yolo26n_vehicle_entry_exit_int8.xml` / `.bin` -- INT8 quantized model *(only when `INT8` is selected)*.
 
152
  overlay or line).
153
  Change the `device` string to run on CPU, GPU, or NPU.
154
 
155
+ The full sample is in [openvino_sample.py](openvino_sample.py); run it with `python3 openvino_sample.py` or copy the code below.
156
+
157
+ <!-- sample: openvino_sample.py -->
158
  ```python
159
+ # SPDX-License-Identifier: MIT
160
+ # Copyright (C) Intel Corporation
161
+ #
162
+ # Vehicle Entry/Exit Logging: OpenVINO Runtime sample.
163
+ # See README.md for prerequisites and inputs. Run: python3 openvino_sample.py
164
+
165
  import cv2
166
  import numpy as np
167
  import openvino as ov
168
 
169
  VEHICLE_CLASS_IDS = {2: "car"}
170
  CONF_THRESHOLD = 0.4
171
+ # Select the model: "yolo26n" (default) or "detr-resnet-50".
172
+ MODEL = "yolo26n"
173
+ INPUT_SIZE = 800 if MODEL.startswith("detr") else 640
174
  LINE_RATIO = 0.6
175
  MAX_DIST = 80
176
 
177
  core = ov.Core()
178
+ model = core.read_model(f"{MODEL}_openvino_model/{MODEL}.xml")
179
 
180
  # Change device to "GPU" or "NPU" to run on integrated GPU or NPU.
181
  compiled = core.compile_model(model, "CPU")
 
276
  writer.release()
277
  print(f"Total: entered={entered} exited={exited}", flush=True)
278
  ```
279
+ <!-- /sample -->
280
 
281
  **Device targets:**
282
 
 
312
 
313
  > **Notes on running this sample:**
314
  >
315
+ > - Use the FP16 IR (`yolo26n_openvino_model/yolo26n.xml` or `detr-resnet-50_openvino_model/detr-resnet-50.xml`). Class names are
316
  > read automatically from the model's embedded `metadata.yaml` by
317
  > DLStreamer 2026.0+ -- no external `labels-file` is required.
318
  > - Detections are read with the `gstgva` `VideoFrame` API
 
326
  > /opt/intel/dlstreamer/gstreamer/lib/python3/dist-packages:${PYTHONPATH:-}
327
  > ```
328
 
329
+ The full sample is in [dlstreamer_sample.py](dlstreamer_sample.py); run it with `python3 dlstreamer_sample.py` or copy the code below.
330
+
331
+ <!-- sample: dlstreamer_sample.py -->
332
  ```python
333
+ # SPDX-License-Identifier: MIT
334
+ # Copyright (C) Intel Corporation
335
+ #
336
+ # Vehicle Entry/Exit Logging: DLStreamer pipeline sample.
337
+ # See README.md for prerequisites and inputs. Run: python3 dlstreamer_sample.py
338
+
339
  import gi
340
 
341
  gi.require_version("Gst", "1.0")
 
348
  VEHICLE_LABELS = {"car"}
349
  LINE_RATIO = 0.6
350
 
351
+ # Select the model: "yolo26n" (default) or "detr-resnet-50".
352
+ MODEL = "yolo26n"
353
+
354
  # For CPU: change device=GPU to device=CPU.
355
  # For NPU: change device=GPU to device=NPU (batch-size=1, nireq=4 recommended).
356
  pipeline_str = (
357
  f"filesrc location={INPUT_VIDEO} ! decodebin3 ! "
358
  "videoconvert ! "
359
+ f"gvadetect model={MODEL}_openvino_model/{MODEL}.xml "
360
  "device=GPU "
361
  "threshold=0.4 ! queue ! "
362
  "gvatrack tracking-type=short-term-imageless ! queue ! "
 
431
  pipeline.set_state(Gst.State.NULL)
432
  print(f"Total: entered={entered} exited={exited}", flush=True)
433
  ```
434
+ <!-- /sample -->
435
 
436
  **Device targets:**
437
 
 
465
  ## References
466
 
467
  - [YOLO26 Documentation](https://docs.ultralytics.com/models/yolo26/)
468
+ - [DETR Model Card (facebook/detr-resnet-50)](https://huggingface.co/facebook/detr-resnet-50)
469
+ - [End-to-End Object Detection with Transformers (DETR paper)](https://arxiv.org/abs/2005.12872)
470
+ - [Intel DLStreamer gvatrack](https://docs.openedgeplatform.intel.com/dev/edge-ai-libraries/dlstreamer/elements/gvatrack.html)
471
  - [BoT-SORT: Robust Multi-Object Tracking](https://arxiv.org/abs/2206.14651)
472
  - [OpenVINO Documentation](https://docs.openvino.ai/)
473
+ - [Intel DLStreamer](https://docs.openedgeplatform.intel.com/dev/edge-ai-libraries/dlstreamer/index.html)
config.json CHANGED
@@ -3,8 +3,8 @@
3
  "library_name": "openvino",
4
  "pipeline_tag": "object-detection",
5
  "category": "Object Detection + Tracking + Line Crossing",
6
- "base_model": "YOLO26 (Ultralytics)",
7
- "source_framework": "PyTorch (Ultralytics)",
8
  "supported_precisions": [
9
  "FP32",
10
  "FP16",
@@ -18,5 +18,13 @@
18
  ],
19
  "detected_classes": "`car` (2), `motorcycle` (3), `bus` (5), `truck` (7)",
20
  "hf_repo_id": "Intel/vehicle-entry-exit-logging",
21
- "description": "Vehicle entry/exit logging use case using YOLO26 vehicle detection with BoT-SORT tracking and virtual line-crossing to log directional entry and exit events"
 
 
 
 
 
 
 
 
22
  }
 
3
  "library_name": "openvino",
4
  "pipeline_tag": "object-detection",
5
  "category": "Object Detection + Tracking + Line Crossing",
6
+ "base_model": "YOLO26 (Ultralytics, default) or DETR facebook/detr-resnet-50 (alternative)",
7
+ "source_framework": "PyTorch (Ultralytics, Hugging Face Transformers)",
8
  "supported_precisions": [
9
  "FP32",
10
  "FP16",
 
18
  ],
19
  "detected_classes": "`car` (2), `motorcycle` (3), `bus` (5), `truck` (7)",
20
  "hf_repo_id": "Intel/vehicle-entry-exit-logging",
21
+ "description": "Vehicle entry/exit logging use case using YOLO26 (default) or DETR vehicle detection with BoT-SORT tracking and virtual line-crossing to log directional entry and exit events",
22
+ "selectable_models": [
23
+ "yolo26n",
24
+ "yolo26s",
25
+ "yolo26m",
26
+ "yolo26l",
27
+ "detr-resnet-50"
28
+ ],
29
+ "default_model": "yolo26n"
30
  }
dlstreamer_sample.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (C) Intel Corporation
3
+ #
4
+ # Vehicle Entry/Exit Logging: DLStreamer pipeline sample.
5
+ # See README.md for prerequisites and inputs. Run: python3 dlstreamer_sample.py
6
+
7
+ import gi
8
+
9
+ gi.require_version("Gst", "1.0")
10
+ from gi.repository import Gst
11
+ from gstgva import VideoFrame
12
+
13
+ Gst.init([])
14
+
15
+ INPUT_VIDEO = "smart_parking_720p_30fps.mp4"
16
+ VEHICLE_LABELS = {"car"}
17
+ LINE_RATIO = 0.6
18
+
19
+ # Select the model: "yolo26n" (default) or "detr-resnet-50".
20
+ MODEL = "yolo26n"
21
+
22
+ # For CPU: change device=GPU to device=CPU.
23
+ # For NPU: change device=GPU to device=NPU (batch-size=1, nireq=4 recommended).
24
+ pipeline_str = (
25
+ f"filesrc location={INPUT_VIDEO} ! decodebin3 ! "
26
+ "videoconvert ! "
27
+ f"gvadetect model={MODEL}_openvino_model/{MODEL}.xml "
28
+ "device=GPU "
29
+ "threshold=0.4 ! queue ! "
30
+ "gvatrack tracking-type=short-term-imageless ! queue ! "
31
+ "identity name=probe ! "
32
+ "gvawatermark displ-cfg=show-roi=car ! "
33
+ "videoconvert ! video/x-raw,format=I420 ! "
34
+ "openh264enc ! h264parse ! "
35
+ "mp4mux ! filesink location=output_dlstreamer.mp4"
36
+ )
37
+ pipeline = Gst.parse_launch(pipeline_str)
38
+
39
+ prev_positions: dict[int, int] = {}
40
+ entry_time: dict[int, float] = {}
41
+ entered = 0
42
+ exited = 0
43
+ frame_height = 0
44
+
45
+
46
+ def fmt_time(seconds: float) -> str:
47
+ """Format elapsed video time as MM:SS.mmm."""
48
+ minutes, secs = divmod(seconds, 60)
49
+ return f"{int(minutes):02d}:{secs:06.3f}"
50
+
51
+
52
+ def on_buffer(pad, info):
53
+ global entered, exited, frame_height
54
+ buf = info.get_buffer()
55
+ caps = pad.get_current_caps()
56
+ if caps and frame_height == 0:
57
+ frame_height = caps.get_structure(0).get_value("height") or 720
58
+ line_y = int(frame_height * LINE_RATIO)
59
+
60
+ t = buf.pts / Gst.SECOND if buf.pts != Gst.CLOCK_TIME_NONE else 0.0
61
+ frame = VideoFrame(buf, caps=caps)
62
+ current: dict[int, int] = {}
63
+ for region in frame.regions():
64
+ if region.label() not in VEHICLE_LABELS:
65
+ continue
66
+ rect = region.rect()
67
+ cy = int(rect.y + rect.h / 2)
68
+ tid = region.object_id()
69
+ current[tid] = cy
70
+ if tid in prev_positions:
71
+ py = prev_positions[tid]
72
+ if py < line_y <= cy:
73
+ exited += 1
74
+ enter_t = entry_time.pop(tid, None)
75
+ if enter_t is not None:
76
+ print(
77
+ f"EXIT track={tid:<3} entry={fmt_time(enter_t)} "
78
+ f"exit={fmt_time(t)}", flush=True)
79
+ else:
80
+ print(f"EXIT track={tid:<3} exit={fmt_time(t)}", flush=True)
81
+ elif py >= line_y > cy:
82
+ entered += 1
83
+ entry_time[tid] = t
84
+ print(f"ENTRY track={tid:<3} entry={fmt_time(t)}", flush=True)
85
+ prev_positions.clear()
86
+ prev_positions.update(current)
87
+ return Gst.PadProbeReturn.OK
88
+
89
+
90
+ probe = pipeline.get_by_name("probe")
91
+ probe.get_static_pad("src").add_probe(Gst.PadProbeType.BUFFER, on_buffer)
92
+
93
+ pipeline.set_state(Gst.State.PLAYING)
94
+ bus = pipeline.get_bus()
95
+ bus.timed_pop_filtered(
96
+ Gst.CLOCK_TIME_NONE,
97
+ Gst.MessageType.EOS | Gst.MessageType.ERROR,
98
+ )
99
+ pipeline.set_state(Gst.State.NULL)
100
+ print(f"Total: entered={entered} exited={exited}", flush=True)
export_and_quantize.sh CHANGED
@@ -2,10 +2,20 @@
2
  # SPDX-License-Identifier: MIT
3
  # Copyright (C) Intel Corporation
4
  #
5
- # Export a YOLO26 detector to OpenVINO IR for the vehicle-entry-exit-logging
6
  # use case with BoT-SORT tracking and virtual-line crossing.
7
  # Usage: ./export_and_quantize.sh [MODEL_VARIANT] [PRECISION]
8
  # Example: ./export_and_quantize.sh yolo26n FP16
 
 
 
 
 
 
 
 
 
 
9
 
10
  set -euo pipefail
11
 
@@ -18,12 +28,20 @@ if [[ "${PRECISION}" != "FP32" && "${PRECISION}" != "FP16" && "${PRECISION}" !=
18
  exit 1
19
  fi
20
 
21
- echo "--- Installing dependencies ---"
22
- if [[ "${PRECISION}" == "INT8" ]]; then
23
- pip install -qU openvino nncf ultralytics
24
- else
25
- pip install -qU openvino ultralytics
26
- fi
 
 
 
 
 
 
 
 
27
 
28
  # Ask for approval before downloading models and sample files
29
  echo ""
@@ -48,6 +66,17 @@ else
48
  echo "WARNING: HuggingFace tracking ping failed (offline?); continuing." >&2
49
  fi
50
  echo ""
 
 
 
 
 
 
 
 
 
 
 
51
  echo "--- Downloading sample test image ---"
52
  if [[ ! -f test.jpg ]]; then
53
  wget -q -O test.jpg https://ultralytics.com/images/bus.jpg
@@ -73,14 +102,92 @@ else
73
  EXPORT_LABEL="FP16"
74
  fi
75
 
76
- echo "--- Exporting ${MODEL_NAME} to OpenVINO IR (${EXPORT_LABEL}) ---"
77
- python3 -c "
 
78
  from ultralytics import YOLO
79
 
80
  model = YOLO('${MODEL_NAME}.pt')
81
- model.export(format='openvino', half=${HALF_FLAG}, dynamic=False, imgsz=640)
82
  print('Export complete: ${MODEL_NAME}_openvino_model/')
83
  "
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
  if [[ "${PRECISION}" == "INT8" ]]; then
86
  echo "--- Quantizing to INT8 with NNCF ---"
@@ -94,7 +201,7 @@ core = ov.Core()
94
  model = core.read_model('${MODEL_NAME}_openvino_model/${MODEL_NAME}.xml')
95
 
96
  img = cv2.imread('test.jpg')
97
- img = cv2.resize(img, (640, 640))
98
  img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
99
  img = img.transpose(2, 0, 1)[np.newaxis, ...]
100
 
@@ -108,6 +215,7 @@ quantized = nncf.quantize(
108
  calibration_dataset,
109
  preset=nncf.QuantizationPreset.MIXED,
110
  subset_size=300,
 
111
  )
112
 
113
  ov.save_model(quantized, '${MODEL_NAME}_vehicle_entry_exit_int8.xml')
 
2
  # SPDX-License-Identifier: MIT
3
  # Copyright (C) Intel Corporation
4
  #
5
+ # Export a YOLO26 or DETR detector to OpenVINO IR for the vehicle-entry-exit-logging
6
  # use case with BoT-SORT tracking and virtual-line crossing.
7
  # Usage: ./export_and_quantize.sh [MODEL_VARIANT] [PRECISION]
8
  # Example: ./export_and_quantize.sh yolo26n FP16
9
+ # Example: ./export_and_quantize.sh detr-resnet-50 FP16
10
+ #
11
+ # Supported model variants:
12
+ # yolo26n, yolo26s, yolo26m, yolo26l -- Ultralytics YOLO26 (default)
13
+ # detr-resnet-50 -- Facebook DETR (Hugging Face)
14
+ #
15
+ # DETR is exported end-to-end: ImageNet normalization, softmax,
16
+ # box decoding, and the COCO-91 to COCO-80 class remap are embedded in the
17
+ # graph, so the IR produces the same [1, N, 6] output layout and class ids as
18
+ # YOLO26 and runs with the same OpenVINO and DLStreamer samples.
19
 
20
  set -euo pipefail
21
 
 
28
  exit 1
29
  fi
30
 
31
+ case "${MODEL_NAME}" in
32
+ yolo26n|yolo26s|yolo26m|yolo26l)
33
+ MODEL_FAMILY="yolo"
34
+ INPUT_SIZE=640
35
+ ;;
36
+ detr-resnet-50)
37
+ MODEL_FAMILY="detr"
38
+ INPUT_SIZE=800
39
+ ;;
40
+ *)
41
+ echo "ERROR: unsupported model '${MODEL_NAME}'. Choose yolo26[n|s|m|l] or detr-resnet-50." >&2
42
+ exit 1
43
+ ;;
44
+ esac
45
 
46
  # Ask for approval before downloading models and sample files
47
  echo ""
 
66
  echo "WARNING: HuggingFace tracking ping failed (offline?); continuing." >&2
67
  fi
68
  echo ""
69
+ echo "--- Installing dependencies ---"
70
+ if [[ "${MODEL_FAMILY}" == "detr" ]]; then
71
+ DEPS=(openvino transformers torch pyyaml opencv-python)
72
+ else
73
+ DEPS=(openvino ultralytics)
74
+ fi
75
+ if [[ "${PRECISION}" == "INT8" ]]; then
76
+ DEPS+=(nncf)
77
+ fi
78
+ pip install -qU "${DEPS[@]}"
79
+
80
  echo "--- Downloading sample test image ---"
81
  if [[ ! -f test.jpg ]]; then
82
  wget -q -O test.jpg https://ultralytics.com/images/bus.jpg
 
102
  EXPORT_LABEL="FP16"
103
  fi
104
 
105
+ if [[ "${MODEL_FAMILY}" == "yolo" ]]; then
106
+ echo "--- Exporting ${MODEL_NAME} to OpenVINO IR (${EXPORT_LABEL}) ---"
107
+ python3 -c "
108
  from ultralytics import YOLO
109
 
110
  model = YOLO('${MODEL_NAME}.pt')
111
+ model.export(format='openvino', half=${HALF_FLAG}, dynamic=False, imgsz=${INPUT_SIZE}, nms=False)
112
  print('Export complete: ${MODEL_NAME}_openvino_model/')
113
  "
114
+ else
115
+ echo "--- Exporting facebook/${MODEL_NAME} to OpenVINO IR (${EXPORT_LABEL}) ---"
116
+ python3 - "${MODEL_NAME}" "${HALF_FLAG}" "${INPUT_SIZE}" <<'PYEXPORT'
117
+ import sys
118
+ from pathlib import Path
119
+
120
+ import openvino as ov
121
+ import torch
122
+ import yaml
123
+ from transformers import DetrForObjectDetection
124
+
125
+ model_name, half_flag, size = sys.argv[1], sys.argv[2] == "True", int(sys.argv[3])
126
+ model_id = f"facebook/{model_name}"
127
+
128
+ # The "no_timm" revision uses the transformers ResNet backbone (no timm dependency).
129
+ detr = DetrForObjectDetection.from_pretrained(model_id, revision="no_timm").eval()
130
+ id2label = detr.config.id2label
131
+ # DETR predicts 91 COCO category ids (with "N/A" gaps) plus a no-object class.
132
+ # Keep the 80 real categories so class ids match YOLO26 (person = 0).
133
+ coco80 = [k for k in sorted(id2label) if id2label[k] != "N/A"]
134
+ assert len(coco80) == 80, f"unexpected label map with {len(coco80)} classes"
135
+
136
+
137
+ class DetrEndToEnd(torch.nn.Module):
138
+ """Input: RGB [0, 1] NCHW. Output: [1, 100, 6] = [x1, y1, x2, y2, conf, class_id] in input pixels."""
139
+
140
+ def __init__(self, model: torch.nn.Module) -> None:
141
+ super().__init__()
142
+ self.model = model
143
+ self.register_buffer("mean", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1))
144
+ self.register_buffer("std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))
145
+ self.register_buffer("coco80", torch.tensor(coco80))
146
+
147
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
148
+ out = self.model(pixel_values=(x - self.mean) / self.std, return_dict=True)
149
+ probs = out.logits.softmax(-1).index_select(-1, self.coco80)
150
+ conf, cls = probs.max(-1)
151
+ cx, cy, w, h = (out.pred_boxes * size).unbind(-1)
152
+ return torch.stack([cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2, conf, cls.float()], -1)
153
+
154
+
155
+ ov_model = ov.convert_model(
156
+ DetrEndToEnd(detr), example_input=torch.zeros(1, 3, size, size), input=[1, 3, size, size]
157
+ )
158
+ ov_model.outputs[0].get_tensor().set_names({"output0"})
159
+
160
+ names = {i: id2label[k] for i, k in enumerate(coco80)}
161
+ # DLStreamer reads preprocessing and the post-processor type from model_info.
162
+ model_info = {
163
+ "model_type": "YOLO",
164
+ "labels": " ".join(n.replace(" ", "_") for n in names.values()),
165
+ "resize_type": "standard",
166
+ "reverse_input_channels": "YES",
167
+ "scale_values": "255",
168
+ "iou_threshold": "0.7",
169
+ }
170
+ for key, value in model_info.items():
171
+ ov_model.set_rt_info(value, ["model_info", key])
172
+
173
+ out_dir = Path(f"{model_name}_openvino_model")
174
+ out_dir.mkdir(exist_ok=True)
175
+ ov.save_model(ov_model, out_dir / f"{model_name}.xml", compress_to_fp16=half_flag)
176
+ metadata = {
177
+ "description": f"{model_id} exported end-to-end with YOLO26-compatible output",
178
+ "license": "Apache-2.0",
179
+ "task": "detect",
180
+ "batch": 1,
181
+ "imgsz": [size, size],
182
+ "names": names,
183
+ "channels": 3,
184
+ "end2end": True,
185
+ }
186
+ with open(out_dir / "metadata.yaml", "w", encoding="utf-8") as f:
187
+ yaml.safe_dump(metadata, f, sort_keys=False)
188
+ print(f"Export complete: {out_dir}/")
189
+ PYEXPORT
190
+ fi
191
 
192
  if [[ "${PRECISION}" == "INT8" ]]; then
193
  echo "--- Quantizing to INT8 with NNCF ---"
 
201
  model = core.read_model('${MODEL_NAME}_openvino_model/${MODEL_NAME}.xml')
202
 
203
  img = cv2.imread('test.jpg')
204
+ img = cv2.resize(img, (${INPUT_SIZE}, ${INPUT_SIZE}))
205
  img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
206
  img = img.transpose(2, 0, 1)[np.newaxis, ...]
207
 
 
215
  calibration_dataset,
216
  preset=nncf.QuantizationPreset.MIXED,
217
  subset_size=300,
218
+ model_type=nncf.ModelType.TRANSFORMER if '${MODEL_FAMILY}' == 'detr' else None,
219
  )
220
 
221
  ov.save_model(quantized, '${MODEL_NAME}_vehicle_entry_exit_int8.xml')
openvino_sample.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (C) Intel Corporation
3
+ #
4
+ # Vehicle Entry/Exit Logging: OpenVINO Runtime sample.
5
+ # See README.md for prerequisites and inputs. Run: python3 openvino_sample.py
6
+
7
+ import cv2
8
+ import numpy as np
9
+ import openvino as ov
10
+
11
+ VEHICLE_CLASS_IDS = {2: "car"}
12
+ CONF_THRESHOLD = 0.4
13
+ # Select the model: "yolo26n" (default) or "detr-resnet-50".
14
+ MODEL = "yolo26n"
15
+ INPUT_SIZE = 800 if MODEL.startswith("detr") else 640
16
+ LINE_RATIO = 0.6
17
+ MAX_DIST = 80
18
+
19
+ core = ov.Core()
20
+ model = core.read_model(f"{MODEL}_openvino_model/{MODEL}.xml")
21
+
22
+ # Change device to "GPU" or "NPU" to run on integrated GPU or NPU.
23
+ compiled = core.compile_model(model, "CPU")
24
+
25
+ cap = cv2.VideoCapture("smart_parking_720p_30fps.mp4")
26
+ fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
27
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
28
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
29
+ line_y = int(height * LINE_RATIO)
30
+
31
+
32
+ def fmt_time(seconds: float) -> str:
33
+ """Format elapsed video time as MM:SS.mmm."""
34
+ minutes, secs = divmod(seconds, 60)
35
+ return f"{int(minutes):02d}:{secs:06.3f}"
36
+
37
+
38
+ writer = cv2.VideoWriter(
39
+ "output_openvino.mp4", cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height))
40
+
41
+ tracks: dict[int, tuple[int, int]] = {}
42
+ entry_time: dict[int, float] = {}
43
+ next_id = 0
44
+ entered = 0
45
+ exited = 0
46
+ frame_idx = 0
47
+
48
+ while True:
49
+ ok, frame = cap.read()
50
+ if not ok:
51
+ break
52
+ frame_idx += 1
53
+ h0, w0 = frame.shape[:2]
54
+ sx, sy = w0 / INPUT_SIZE, h0 / INPUT_SIZE
55
+
56
+ blob = cv2.resize(frame, (INPUT_SIZE, INPUT_SIZE))
57
+ blob = cv2.cvtColor(blob, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
58
+ blob = blob.transpose(2, 0, 1)[np.newaxis, ...]
59
+
60
+ output = compiled([blob])[compiled.output(0)][0]
61
+ mask = (output[:, 4] >= CONF_THRESHOLD) & np.isin(
62
+ output[:, 5].astype(int), list(VEHICLE_CLASS_IDS.keys()))
63
+ dets = output[mask]
64
+
65
+ centroids = []
66
+ for det in dets:
67
+ cx = int(((det[0] + det[2]) / 2) * sx)
68
+ cy = int(((det[1] + det[3]) / 2) * sy)
69
+ centroids.append((cx, cy))
70
+
71
+ new_tracks: dict[int, tuple[int, int]] = {}
72
+ used = set()
73
+ for tid, (px, py) in tracks.items():
74
+ best_d = MAX_DIST
75
+ best_j = -1
76
+ for j, (cx, cy) in enumerate(centroids):
77
+ if j in used:
78
+ continue
79
+ d = abs(cx - px) + abs(cy - py)
80
+ if d < best_d:
81
+ best_d = d
82
+ best_j = j
83
+ if best_j >= 0:
84
+ cx, cy = centroids[best_j]
85
+ used.add(best_j)
86
+ t = frame_idx / fps
87
+ if py < line_y <= cy:
88
+ exited += 1
89
+ enter_t = entry_time.pop(tid, None)
90
+ if enter_t is not None:
91
+ print(
92
+ f"EXIT track={tid:<3} entry={fmt_time(enter_t)} "
93
+ f"exit={fmt_time(t)}", flush=True)
94
+ else:
95
+ print(f"EXIT track={tid:<3} exit={fmt_time(t)}", flush=True)
96
+ elif py >= line_y > cy:
97
+ entered += 1
98
+ entry_time[tid] = t
99
+ print(f"ENTRY track={tid:<3} entry={fmt_time(t)}", flush=True)
100
+ new_tracks[tid] = (cx, cy)
101
+ for j, (cx, cy) in enumerate(centroids):
102
+ if j not in used:
103
+ new_tracks[next_id] = (cx, cy)
104
+ next_id += 1
105
+ tracks = new_tracks
106
+
107
+ for det in dets:
108
+ x1 = int(det[0] * sx)
109
+ y1 = int(det[1] * sy)
110
+ x2 = int(det[2] * sx)
111
+ y2 = int(det[3] * sy)
112
+ cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
113
+ cv2.putText(frame, "car", (x1, max(y1 - 6, 0)),
114
+ cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
115
+ writer.write(frame)
116
+
117
+ cap.release()
118
+ writer.release()
119
+ print(f"Total: entered={entered} exited={exited}", flush=True)