Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
116180a62c | ||
|
|
3f292ca249 |
No files matched your search
+2
-2
@@ -17,10 +17,10 @@ current_batch.json
|
||||
bytetrack_current_batch.json
|
||||
batch_crossings.csv
|
||||
|
||||
# Models / binaries
|
||||
# Models / binaries — track only .pt; converted artifacts stay local
|
||||
*.rknn
|
||||
*.pt
|
||||
*.onnx
|
||||
*.engine
|
||||
|
||||
# Runtime artifacts
|
||||
/dev/shm/
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
|
||||
## Project Overview
|
||||
|
||||
Feedmill is a production edge counter for feed sacks and boxes. A Rockchip RK3588 NPU runs YOLO (RKNN) over an RTSP camera stream; ByteTrack tracks objects; a line-crossing rule increments counts. Counts persist to SQLite + JSON state; a Flask dashboard on port 7000 exposes batch control and reporting. Truck detections are used only to define the horizontal counting zone, not counted.
|
||||
Feedmill is a production edge counter for feed sacks and boxes. YOLO runs on edge hardware over an RTSP camera stream — NVIDIA Jetson (TensorRT, `.engine`) or Rockchip RK3588 NPU (RKNN, `.rknn`); backend is picked by `MODEL_PATH` suffix. ByteTrack tracks objects; a line-crossing rule increments counts. Counts persist to SQLite + JSON state; a Flask dashboard on port 7000 exposes batch control and reporting. Truck detections are used only to define the horizontal counting zone, not counted.
|
||||
|
||||
## Architecture & Data Flow
|
||||
|
||||
1. Camera: `connect_stream(SOURCE)` in `counter_live_rknn.py:run()` reads RTSP frames.
|
||||
2. Optional motion gate skips inference when frame diff is below `MOTION_THRESHOLD`.
|
||||
3. Inference: `RKNNYOLO.__call__` (RKNN on NPU) returns detections.
|
||||
3. Inference: `create_model(MODEL_PATH)` picks `TRTYOLO` (`.engine`/`.trt`) or `RKNNYOLO` (`.rknn`); both subclass `YOLODetector` (shared letterbox preprocess + decode) and `_infer` returns raw output tensors.
|
||||
4. Detections filtered by active batch class IDs (`0=sack`, `1=box`) and horizontal zone (`zone_x1..zone_x2`).
|
||||
5. Tracking: `ByteTracker.update` associates detections across frames.
|
||||
6. Crossing: `crossed_line(prev_pos, pos, line_pos)` plus `is_duplicate_cross` dedup; on crossing, `BatchStore.record_counted_object_crossing(tid, object_label=...)`.
|
||||
@@ -19,19 +19,20 @@ Batches: manual mode (operator start/stop; passing objects ignored while stopped
|
||||
|
||||
## Key Directories
|
||||
|
||||
- `/` — runtime modules and config: `counter_live_rknn.py`, `batch_store.py`, `counter_control.py`, `counter_dashboard.py`, `.env`, `config.env.example`.
|
||||
- `/` — runtime modules and config: `counter_live_rknn.py`, `batch_store.py`, `counter_control.py`, `counter_dashboard.py`, `convert_models.py` (pt→engine), `convert_to_rknn.py` (pt→rknn), `.env`, `config.env.example`.
|
||||
- `tests/` — stdlib `unittest` suites.
|
||||
- `docs/` — peer-sync and unified-batch specs/plans.
|
||||
- `templates/` — `dashboard.html` (Jinja, Chart.js).
|
||||
- `static/img/` — logos/icons.
|
||||
- `/opt/models/` — `.rknn` model files (outside repo).
|
||||
- `model/` — `.pt` tracked; `.onnx`/`.engine`/`.rknn` gitignored (build via `convert_models.py` / `convert_to_rknn.py`). `/opt/models/` used in production (outside repo).
|
||||
|
||||
## Development Commands
|
||||
|
||||
```bash
|
||||
# venv
|
||||
python3 -m venv /opt/feedmill/venv
|
||||
/opt/feedmill/venv/bin/pip install -r requirements.txt
|
||||
/opt/feedmill/venv/bin/pip install -r requirements.txt -r requirements-jetson.txt # Jetson
|
||||
/opt/feedmill/venv/bin/pip install -r requirements.txt -r requirements-rknn.txt # NanoPi
|
||||
|
||||
# run counter
|
||||
/opt/feedmill/venv/bin/python /opt/feedmill/counter_live_rknn.py
|
||||
@@ -49,7 +50,7 @@ sudo ./install-services.sh
|
||||
sudo ./uninstall-services.sh
|
||||
```
|
||||
|
||||
No build step, lint config, or package manifest beyond `requirements.txt`.
|
||||
No build step, lint config, or package manifest beyond `requirements*.txt`.
|
||||
|
||||
## Code Conventions & Common Patterns
|
||||
|
||||
@@ -64,20 +65,20 @@ No build step, lint config, or package manifest beyond `requirements.txt`.
|
||||
|
||||
## Important Files
|
||||
|
||||
- `counter_live_rknn.py` — main pipeline entry (`if __name__ == "__main__": run()`), RKNN wrapper, ByteTrack, crossing logic.
|
||||
- `counter_live_rknn.py` — main pipeline entry (`if __name__ == "__main__": run()`), backend wrappers (`YOLODetector`/`RKNNYOLO`/`TRTYOLO`, `create_model`), ByteTrack, crossing logic.
|
||||
- `batch_store.py` — SQLite schema migration, `BatchStore`, batch lifecycle, cutoff watcher.
|
||||
- `counter_control.py` — internal HTTP control server (`/status`, `/start*`, `/stop`).
|
||||
- `counter_dashboard.py` — Flask app, reporting, XLSX export, peer sync.
|
||||
- `config.env.example` / `.env` — all runtime configuration.
|
||||
- `requirements.txt` — Python dependencies.
|
||||
- `requirements.txt` (common) + `requirements-jetson.txt` (pycuda; tensorrt from JetPack) + `requirements-rknn.txt` (rknn-toolkit-lite2) — Python dependencies.
|
||||
- `feedmill-counter.service`, `feedmill-dashboard.service` — systemd units.
|
||||
- `API.md`, `DEPLOY.md`, `README.md` — API, deployment, overview docs.
|
||||
|
||||
## Runtime/Tooling Preferences
|
||||
|
||||
- Python 3.12.3 in `/opt/feedmill/venv` (system-site-packages false).
|
||||
- Dependencies: `numpy<2`, `rknn-toolkit-lite2`, `opencv-python`, `flask`, `python-dotenv`, `openpyxl`.
|
||||
- RKNN runtime 2.3.2 targeting RKNPU v2 (RK3588). Models live in `/opt/models/*.rknn`.
|
||||
- Python 3.12 venv at `/opt/feedmill/venv` with `--system-site-packages` (JetPack `tensorrt` visible).
|
||||
- Dependencies: `numpy<2`, `opencv-python`, `flask`, `python-dotenv`, `openpyxl`, plus platform backend: RKNN runtime (`rknn-toolkit-lite2`, RK3588) or `tensorrt`+`pycuda` (Jetson).
|
||||
- Models: `.rknn` (float, rk3588, via `convert_to_rknn.py` — needs `/dev/rknpu`, so run on NanoPi/x86) or `.engine` (`convert_models.py`, on Jetson). `NUM_CLASSES` must match model (3).
|
||||
- Install scripts require root; services run as root with `PYTHONNOUSERSITE=1`.
|
||||
- No Node/Bun tooling; frontend is server-rendered Jinja + Chart.js.
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
# Edge RKNN Deploy
|
||||
# Edge Deploy
|
||||
|
||||
Production counter: **direct LAN RTSP** + **YOLO RKNN** + **ByteTrack** + SQLite batch store + Flask dashboard + FCP peer sync.
|
||||
Production counter: **direct LAN RTSP** + **YOLO** (RKNN on RK3588 / TensorRT on Jetson) + **ByteTrack** + SQLite batch store + Flask dashboard + FCP peer sync.
|
||||
|
||||
## Quick install
|
||||
|
||||
```bash
|
||||
# 1. Copy this folder to the RK3588 device
|
||||
# 1. Copy this folder to the target device (NanoPi RK3588 or Jetson)
|
||||
sudo mkdir -p /opt/feedmill
|
||||
sudo cp -r feedmill/* /opt/feedmill/
|
||||
sudo chown -R $(whoami):$(whoami) /opt/feedmill
|
||||
@@ -28,14 +28,19 @@ Dashboard: `http://<ip-device>:7000` (internal control: `127.0.0.1:5000`).
|
||||
|
||||
## Model checklist
|
||||
|
||||
Set `.env` to the exported `.rknn` model path and make sure class order matches:
|
||||
Backend follows the `MODEL_PATH` suffix: `.rknn` → RKNN (NanoPi), `.engine`/`.trt` → TensorRT (Jetson).
|
||||
|
||||
1. `NUM_CLASSES=3` (sack, box, truck)
|
||||
- **Jetson:** convert `.pt` → `.engine` with `convert_models.py` (uses ultralytics + TensorRT, run on the Jetson).
|
||||
- **NanoPi:** convert `.pt` → `.onnx` → `.rknn` with `convert_to_rknn.py`. rknn-toolkit2 needs `/dev/rknpu` (Rockchip host) — run it on the NanoPi or an x86 PC, not on Jetson.
|
||||
|
||||
Set `.env` so class order matches:
|
||||
|
||||
1. `NUM_CLASSES=3` (sack, box, truck) — required; the `.engine` output layout is decoded with it (wrong value drops box/truck)
|
||||
2. `COUNTED_CLASS_IDS=0,1` (sack + box counted)
|
||||
3. `TRUCK_CLASS_ID=2` (truck defines counting zone only)
|
||||
4. `COUNT_AXIS=y`
|
||||
5. `CROSS_DIRECTION=down`
|
||||
6. `MODEL_PATH=/opt/models/y11_11_20.rknn`, `IMGSZ=320`
|
||||
6. `MODEL_PATH` → your model (e.g. `/opt/models/y11_11_20.rknn` or `.../zenai_fcp_20261120.engine`), `IMGSZ=320`
|
||||
|
||||
---
|
||||
|
||||
@@ -60,14 +65,17 @@ nc -zv <camera-ip> 554
|
||||
|
||||
```bash
|
||||
sudo systemctl is-active feedmill-counter feedmill-dashboard
|
||||
# NanoPi (RKNN):
|
||||
PYTHONNOUSERSITE=1 /opt/feedmill/venv/bin/python -c "from rknnlite.api import RKNNLite; print('rknn ok')"
|
||||
# Jetson (TensorRT):
|
||||
PYTHONNOUSERSITE=1 /opt/feedmill/venv/bin/python -c "import tensorrt, pycuda.driver; print('trt ok')"
|
||||
sudo journalctl -u feedmill-counter -n 20 --no-pager
|
||||
```
|
||||
|
||||
Good signs:
|
||||
|
||||
- `Stream ready!`
|
||||
- `RKNN model loaded: ...`
|
||||
- `RKNN model loaded: ...` or `TensorRT engine loaded: ...`
|
||||
- `Frame 100 | Batch ...`
|
||||
|
||||
---
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
# RKNN Sack Counter (Production)
|
||||
# Edge Sack Counter (Production)
|
||||
|
||||
RTSP + YOLO RKNN + ByteTrack line-crossing counter for **sacks**, **boxes**, and **trucks** (truck = zone only) on Rockchip edge hardware. Unified batches report separate Sack and Box totals.
|
||||
RTSP + YOLO + ByteTrack line-crossing counter for **sacks**, **boxes**, and **trucks** (truck = zone only) on edge hardware: NVIDIA Jetson (TensorRT) and Rockchip RK3588 (RKNN). Unified batches report separate Sack and Box totals.
|
||||
|
||||
## Architecture
|
||||
|
||||
- **Input:** Direct LAN camera RTSP (low latency)
|
||||
- **Inference:** YOLO `.rknn` on RK3588 NPU (3 classes: sack=0, box=1, truck=2)
|
||||
- **Inference:** YOLO with backend selected by `MODEL_PATH` suffix — `.engine`/`.trt` → TensorRT (Jetson), `.rknn` → RKNN (RK3588 NPU). 3 classes: sack=0, box=1, truck=2
|
||||
- **Logic:** Line crossing (`sack` + `box` counts) via `batch_store.py`; truck bbox defines horizontal counting zone
|
||||
- **Output:** `feedmill.db` + `current_batch.json` (+ optional CSV/video/live frame)
|
||||
- **Dashboard:** Flask on port **7000**; internal control server on `127.0.0.1:5000`
|
||||
@@ -40,7 +40,7 @@ See **[DEPLOY.md](DEPLOY.md)**.
|
||||
| Variable | Purpose |
|
||||
|----------|---------|
|
||||
| `SOURCE` | Direct camera RTSP URL |
|
||||
| `MODEL_PATH` | `.rknn` file path (`/opt/models/y11_11_20.rknn`) |
|
||||
| `MODEL_PATH` | Model file; suffix picks backend: `.rknn` (RK3588) or `.engine` (Jetson) |
|
||||
| `NUM_CLASSES` | Model class count (3: sack, box, truck) |
|
||||
| `COUNTED_CLASS_IDS` | Counted class IDs (0,1) |
|
||||
| `TRUCK_CLASS_ID` | Truck class ID for zone (2) |
|
||||
@@ -56,11 +56,14 @@ See **[DEPLOY.md](DEPLOY.md)**.
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `counter_live_rknn.py` | RTSP + RKNN YOLO + ByteTrack line crossing |
|
||||
| `counter_live_rknn.py` | RTSP + YOLO (RKNN/TensorRT backend) + ByteTrack line crossing |
|
||||
| `batch_store.py` | SQLite persistence, unified batches, schema migration |
|
||||
| `counter_control.py` | Internal HTTP control server (127.0.0.1:5000) |
|
||||
| `counter_dashboard.py` | Flask UI, reporting, XLSX export, peer sync |
|
||||
| `config.env.example` | Env template |
|
||||
| `convert_models.py` | Jetson: `.pt` → `.onnx` → `.engine` (TensorRT, `imgsz=320`) |
|
||||
| `convert_to_rknn.py` | `.pt` → `.onnx` → `.rknn` float export for `rk3588` (run on x86 or a Rockchip host with `/dev/rknpu`) |
|
||||
| `requirements.txt` / `requirements-jetson.txt` / `requirements-rknn.txt` | Common deps + per-platform backend deps |
|
||||
| `feedmill-counter.service` | Counter systemd unit |
|
||||
| `feedmill-dashboard.service` | Dashboard systemd unit |
|
||||
| `install-services.sh` / `setup-venv.sh` | Install / venv setup |
|
||||
|
||||
+5
-5
@@ -19,21 +19,21 @@ SOURCE=rtsp://user:pass@192.168.0.100:554/stream1
|
||||
# FFmpeg capture options passed to cv2.VideoCapture (RTSP low-latency flags)
|
||||
OPENCV_FFMPEG_CAPTURE_OPTIONS=rtsp_transport;tcp|fflags;nobuffer|flags;low_delay
|
||||
|
||||
# --- RKNN model ---
|
||||
# Path to exported .rknn model (YOLO format, e.g. yolo11n.rknn)
|
||||
# --- Model (suffix selects backend: .rknn → RKNN / RK3588, .engine/.trt → TensorRT / Jetson) ---
|
||||
# Model file: .rknn exported with convert_to_rknn.py (NanoPi), .engine exported with convert_models.py (Jetson)
|
||||
MODEL_PATH=/opt/models/yolo9t.rknn
|
||||
# Input image size for the model (square, e.g. 320 → 320×320)
|
||||
IMGSZ=320
|
||||
# Use FP16 inference on NPU (true/false); currently unused in ByteTrack variant
|
||||
HALF=false
|
||||
# NPU core mask: 1=core0, 2=core1, 3=core0+core1, 7=all three
|
||||
# NPU core mask for RKNN backend only (1=core0, 2=core1, 3=core0+core1, 7=all three); ignored by TensorRT
|
||||
CORE_MASK=7
|
||||
# Compute device index (reserved; not used at runtime)
|
||||
DEVICE=0
|
||||
|
||||
# --- YOLO decoder ---
|
||||
# Number of object classes the model outputs (1 = sack only)
|
||||
NUM_CLASSES=1
|
||||
# Number of object classes the model outputs (3 = sack, box, truck); must match the model — decoder misdetects output layout if wrong
|
||||
NUM_CLASSES=3
|
||||
# Apply sigmoid to raw class scores (true/false); set true if model head uses BCE logits
|
||||
SCORE_SIGMOID=false
|
||||
|
||||
|
||||
Executable
+33
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Convert model/*.pt checkpoints to ONNX and TensorRT .engine files.
|
||||
|
||||
Each export runs in its own subprocess: exporting ONNX (imports onnxruntime)
|
||||
and then an engine in one process leaves torch.cuda unavailable on this Jetson.
|
||||
"""
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
MODEL_DIR = Path(__file__).parent / "model"
|
||||
IMGSZ = 320 # matches train_args imgsz of the checkpoints
|
||||
|
||||
def export(pt: Path, fmt: str) -> None:
|
||||
code = (
|
||||
"from ultralytics import YOLO; "
|
||||
f"YOLO({str(pt)!r}).export(format={fmt!r}, imgsz={IMGSZ})"
|
||||
)
|
||||
subprocess.run([sys.executable, "-c", code], check=True)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
pts = sorted(MODEL_DIR.glob("*.pt"))
|
||||
if not pts:
|
||||
raise SystemExit(f"no .pt files in {MODEL_DIR}")
|
||||
for pt in pts:
|
||||
for fmt in ("onnx", "engine"):
|
||||
print(f"=== {pt.name} -> {fmt}", flush=True)
|
||||
export(pt, fmt)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+71
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Convert model/*.pt checkpoints to .rknn (RK3588) via ONNX.
|
||||
|
||||
Conversion-time only: needs rknn-toolkit2 (not rknn-toolkit-lite2, which is
|
||||
the NanoPi serving runtime). ONNX export runs in its own subprocess like
|
||||
convert_models.py; rknn-toolkit2 pins its own onnx version, so the two
|
||||
scripts are kept separate.
|
||||
|
||||
Recipe matches counter_live_rknn.py feeding uint8 RGB (1,H,W,3):
|
||||
mean 0 / std 255 normalizes 0-255 -> 0-1 inside the graph.
|
||||
Float build (no quantization) for parity with the Jetson engine.
|
||||
"""
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from rknn.api import RKNN
|
||||
|
||||
MODEL_DIR = Path(__file__).parent / "model"
|
||||
IMGSZ = 320
|
||||
TARGET_PLATFORM = "rk3588"
|
||||
ONNX_OPSET = 13 # rknn-toolkit2 rejects newer opsets
|
||||
|
||||
|
||||
def export_onnx(pt: Path) -> Path:
|
||||
code = (
|
||||
"from ultralytics import YOLO; "
|
||||
f"YOLO({str(pt)!r}).export(format='onnx', imgsz={IMGSZ}, opset={ONNX_OPSET})"
|
||||
)
|
||||
subprocess.run([sys.executable, "-c", code], check=True)
|
||||
onnx = pt.with_suffix(".onnx")
|
||||
if not onnx.exists():
|
||||
raise SystemExit(f"onnx export missing: {onnx}")
|
||||
return onnx
|
||||
|
||||
|
||||
def to_rknn(pt: Path) -> None:
|
||||
onnx = export_onnx(pt)
|
||||
rknn_path = pt.with_suffix(".rknn")
|
||||
print(f"=== {pt.name} -> {rknn_path.name} (onnx {onnx.name})", flush=True)
|
||||
rknn = RKNN(verbose=False)
|
||||
try:
|
||||
rknn.config(
|
||||
mean_values=[[0, 0, 0]],
|
||||
std_values=[[255, 255, 255]],
|
||||
target_platform=TARGET_PLATFORM,
|
||||
)
|
||||
ret = rknn.load_onnx(model=str(onnx))
|
||||
if ret != 0:
|
||||
raise SystemExit(f"load_onnx failed: {onnx}")
|
||||
ret = rknn.build(do_quantization=False)
|
||||
if ret != 0:
|
||||
raise SystemExit(f"rknn build failed: {pt}")
|
||||
ret = rknn.export_rknn(str(rknn_path))
|
||||
if ret != 0:
|
||||
raise SystemExit(f"export_rknn failed: {rknn_path}")
|
||||
finally:
|
||||
rknn.release()
|
||||
print(f"OK: {rknn_path} ({rknn_path.stat().st_size} bytes)", flush=True)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
pts = sorted(MODEL_DIR.glob("*.pt"))
|
||||
if not pts:
|
||||
raise SystemExit(f"no .pt files in {MODEL_DIR}")
|
||||
for pt in pts:
|
||||
to_rknn(pt)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+148
-21
@@ -8,6 +8,7 @@ import contextlib
|
||||
import numpy as np
|
||||
import cv2
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
@@ -20,7 +21,6 @@ from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
from rknnlite.api import RKNNLite
|
||||
from batch_store import BatchStore
|
||||
from counter_control import start_control_server
|
||||
|
||||
@@ -530,11 +530,11 @@ def _xywhr_to_corners(cx, cy, w, h, angle):
|
||||
return np.stack([p1, p2, p3, p4], axis=1)
|
||||
|
||||
|
||||
class RKNNYOLO:
|
||||
class YOLODetector:
|
||||
"""Shared letterbox preprocess + decode; backends implement _infer/release."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model_path,
|
||||
core_mask=1,
|
||||
imgsz=320,
|
||||
conf=0.3,
|
||||
iou=0.45,
|
||||
@@ -549,21 +549,11 @@ class RKNNYOLO:
|
||||
self.num_keypoints = num_keypoints
|
||||
self.score_sigmoid = score_sigmoid
|
||||
|
||||
self.rknn = RKNNLite(verbose=False)
|
||||
ret = self.rknn.load_rknn(model_path)
|
||||
if ret != 0:
|
||||
raise RuntimeError(f"Failed to load RKNN model: {model_path}")
|
||||
ret = self.rknn.init_runtime(core_mask=core_mask)
|
||||
if ret != 0:
|
||||
raise RuntimeError(f"Failed to init RKNN runtime (core_mask={core_mask})")
|
||||
def _infer(self, inp):
|
||||
raise NotImplementedError
|
||||
|
||||
try:
|
||||
sdk_ver = self.rknn.get_sdk_version()
|
||||
print(f"RKNN SDK version: {sdk_ver}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
print(f"RKNN model loaded: {model_path} imgsz={imgsz} core_mask={core_mask}")
|
||||
def release(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def _preprocess(self, frame):
|
||||
h0, w0 = frame.shape[:2]
|
||||
@@ -682,7 +672,7 @@ class RKNNYOLO:
|
||||
inp = np.expand_dims(rgb, axis=0)
|
||||
inp = np.ascontiguousarray(inp.astype(np.uint8))
|
||||
|
||||
outputs = self.rknn.inference(inputs=[inp])
|
||||
outputs = self._infer(inp)
|
||||
|
||||
if len(outputs) == 0:
|
||||
return []
|
||||
@@ -787,10 +777,147 @@ class RKNNYOLO:
|
||||
)
|
||||
return detections
|
||||
|
||||
class RKNNYOLO(YOLODetector):
|
||||
backend = "RKNN"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model_path,
|
||||
core_mask=1,
|
||||
imgsz=320,
|
||||
conf=0.3,
|
||||
iou=0.45,
|
||||
num_classes=1,
|
||||
num_keypoints=0,
|
||||
score_sigmoid=False,
|
||||
):
|
||||
super().__init__(
|
||||
imgsz=imgsz,
|
||||
conf=conf,
|
||||
iou=iou,
|
||||
num_classes=num_classes,
|
||||
num_keypoints=num_keypoints,
|
||||
score_sigmoid=score_sigmoid,
|
||||
)
|
||||
from rknnlite.api import RKNNLite # lazy: Jetson has no rknnlite
|
||||
|
||||
self.rknn = RKNNLite(verbose=False)
|
||||
ret = self.rknn.load_rknn(model_path)
|
||||
if ret != 0:
|
||||
raise RuntimeError(f"Failed to load RKNN model: {model_path}")
|
||||
ret = self.rknn.init_runtime(core_mask=core_mask)
|
||||
if ret != 0:
|
||||
raise RuntimeError(f"Failed to init RKNN runtime (core_mask={core_mask})")
|
||||
|
||||
try:
|
||||
sdk_ver = self.rknn.get_sdk_version()
|
||||
print(f"RKNN SDK version: {sdk_ver}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
print(f"RKNN model loaded: {model_path} imgsz={imgsz} core_mask={core_mask}")
|
||||
|
||||
def _infer(self, inp):
|
||||
return self.rknn.inference(inputs=[inp])
|
||||
|
||||
def release(self):
|
||||
self.rknn.release()
|
||||
|
||||
|
||||
class TRTYOLO(YOLODetector):
|
||||
"""TensorRT engine backend (Jetson); same letterbox + decode as RKNN."""
|
||||
|
||||
backend = "TensorRT"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model_path,
|
||||
core_mask=None,
|
||||
imgsz=320,
|
||||
conf=0.3,
|
||||
iou=0.45,
|
||||
num_classes=1,
|
||||
num_keypoints=0,
|
||||
score_sigmoid=False,
|
||||
):
|
||||
super().__init__(
|
||||
imgsz=imgsz,
|
||||
conf=conf,
|
||||
iou=iou,
|
||||
num_classes=num_classes,
|
||||
num_keypoints=num_keypoints,
|
||||
score_sigmoid=score_sigmoid,
|
||||
)
|
||||
import pycuda.autoinit # noqa: F401 - one CUDA context per process
|
||||
import pycuda.driver as cuda
|
||||
import tensorrt as trt
|
||||
|
||||
self._cuda = cuda
|
||||
runtime = trt.Runtime(trt.Logger(trt.Logger.WARNING))
|
||||
with open(model_path, "rb") as f:
|
||||
raw = f.read()
|
||||
# ultralytics .engine files prefix metadata: u32 LE length + JSON (same strip as ultralytics autobackend)
|
||||
try:
|
||||
meta_len = int.from_bytes(raw[:4], "little")
|
||||
json.loads(raw[4 : 4 + meta_len].decode("utf-8"))
|
||||
raw = raw[4 + meta_len :]
|
||||
except (UnicodeDecodeError, ValueError):
|
||||
pass # plain engine, no metadata prefix
|
||||
self.engine = runtime.deserialize_cuda_engine(raw)
|
||||
if self.engine is None:
|
||||
raise RuntimeError(f"Failed to load TensorRT engine: {model_path}")
|
||||
self.context = self.engine.create_execution_context()
|
||||
self.stream = cuda.Stream()
|
||||
|
||||
in_name = out_name = None
|
||||
for i in range(self.engine.num_io_tensors):
|
||||
name = self.engine.get_tensor_name(i)
|
||||
if self.engine.get_tensor_mode(name) == trt.TensorIOMode.INPUT:
|
||||
in_name = name
|
||||
else:
|
||||
out_name = name
|
||||
|
||||
in_shape = tuple(self.engine.get_tensor_shape(in_name))
|
||||
if len(in_shape) != 4 or in_shape[2] != imgsz or in_shape[3] != imgsz:
|
||||
raise RuntimeError(
|
||||
f"Engine input {in_shape} does not match imgsz={imgsz}; rebuild engine or set IMGSZ"
|
||||
)
|
||||
self._in_name = in_name
|
||||
self._out_name = out_name
|
||||
self.host_in = np.empty(in_shape, dtype=np.float32)
|
||||
self.host_out = np.empty(
|
||||
tuple(self.engine.get_tensor_shape(out_name)), dtype=np.float32
|
||||
)
|
||||
self.dev_in = cuda.mem_alloc(self.host_in.nbytes)
|
||||
self.dev_out = cuda.mem_alloc(self.host_out.nbytes)
|
||||
self.context.set_tensor_address(in_name, int(self.dev_in))
|
||||
self.context.set_tensor_address(out_name, int(self.dev_out))
|
||||
print(f"TensorRT engine loaded: {model_path} imgsz={imgsz}")
|
||||
# warmup: first inference compiles CUDA kernels (~1s)
|
||||
self._infer(np.zeros((1, imgsz, imgsz, 3), dtype=np.uint8))
|
||||
|
||||
def _infer(self, inp):
|
||||
x = inp.astype(np.float32).transpose(0, 3, 1, 2) / 255.0
|
||||
np.copyto(self.host_in, x)
|
||||
self._cuda.memcpy_htod_async(self.dev_in, self.host_in, self.stream)
|
||||
if not self.context.execute_async_v3(self.stream.handle):
|
||||
raise RuntimeError("TensorRT execute_async_v3 failed")
|
||||
self._cuda.memcpy_dtoh_async(self.host_out, self.dev_out, self.stream)
|
||||
self.stream.synchronize()
|
||||
return [self.host_out]
|
||||
|
||||
def release(self):
|
||||
self.context = None
|
||||
self.engine = None
|
||||
|
||||
|
||||
def create_model(model_path, **kwargs):
|
||||
"""Backend from model extension: .engine/.trt -> TensorRT, .rknn -> RKNN."""
|
||||
if Path(model_path).suffix.lower() in {".engine", ".trt"}:
|
||||
return TRTYOLO(model_path, **kwargs)
|
||||
return RKNNYOLO(model_path, **kwargs)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Drawing helpers
|
||||
# =============================================================================
|
||||
@@ -1327,7 +1454,7 @@ def run():
|
||||
CROSS_CSV, ["batch", "frame", "timestamp", "object_id"]
|
||||
)
|
||||
|
||||
model = RKNNYOLO(
|
||||
model = create_model(
|
||||
model_path=MODEL_PATH,
|
||||
core_mask=CORE_MASK,
|
||||
imgsz=IMGSZ,
|
||||
@@ -1398,7 +1525,7 @@ def run():
|
||||
prev_batch_key = (store.current_batch_number or 0, store.current_batch_object_label)
|
||||
|
||||
print(
|
||||
f"RKNN+ByteTrack counter | {w}x{h} @ {fps}fps | axis={count_axis} line={line_pos} | cross={CROSS_DIRECTION}"
|
||||
f"{model.backend}+ByteTrack counter | {w}x{h} @ {fps}fps | axis={count_axis} line={line_pos} | cross={CROSS_DIRECTION}"
|
||||
)
|
||||
print(f"Model: {MODEL_PATH} | imgsz={IMGSZ} | core_mask={CORE_MASK}")
|
||||
print(
|
||||
|
||||
+7
-2
@@ -46,11 +46,16 @@ done
|
||||
|
||||
chown -R "${SERVICE_USER}:${SERVICE_USER}" "${INSTALL_DIR}"
|
||||
|
||||
if [[ -f /etc/nv_tegra_release ]]; then
|
||||
BACKEND_SMOKE="import tensorrt, pycuda.driver"
|
||||
else
|
||||
BACKEND_SMOKE="from rknnlite.api import RKNNLite"
|
||||
fi
|
||||
PYTHONNOUSERSITE=1 "${VENV_DIR}/bin/python" -c "
|
||||
from rknnlite.api import RKNNLite
|
||||
${BACKEND_SMOKE}
|
||||
import cv2
|
||||
from flask import Flask
|
||||
print('import ok | rknn + opencv + flask')
|
||||
print('import ok | backend + opencv + flask')
|
||||
" || {
|
||||
echo "Import check failed — fix venv before starting services."
|
||||
exit 1
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,5 @@
|
||||
# tensorrt ships with JetPack in /usr/lib/python3.10/dist-packages;
|
||||
# venv runs with --system-site-packages, so no pip install needed.
|
||||
# pycuda has no aarch64 wheel: built from source, needs nvcc (/usr/local/cuda)
|
||||
# and boost headers (libboost-dev).
|
||||
pycuda
|
||||
@@ -0,0 +1 @@
|
||||
rknn-toolkit-lite2
|
||||
@@ -1,5 +1,4 @@
|
||||
numpy<2
|
||||
rknn-toolkit-lite2
|
||||
opencv-python
|
||||
flask
|
||||
python-dotenv
|
||||
|
||||
+17
-3
@@ -20,15 +20,29 @@ fi
|
||||
chown -R "${SERVICE_USER}:${SERVICE_USER}" "${INSTALL_DIR}"
|
||||
|
||||
sudo -u "${SERVICE_USER}" "${VENV_DIR}/bin/pip" install --upgrade pip
|
||||
sudo -u "${SERVICE_USER}" "${VENV_DIR}/bin/pip" install -r "${INSTALL_DIR}/requirements.txt"
|
||||
|
||||
# Platform backend: Jetson (TensorRT) vs NanoPi (RKNN)
|
||||
if [[ -f /etc/nv_tegra_release ]]; then
|
||||
PLATFORM_REQS="${INSTALL_DIR}/requirements-jetson.txt"
|
||||
else
|
||||
PLATFORM_REQS="${INSTALL_DIR}/requirements-rknn.txt"
|
||||
fi
|
||||
sudo -u "${SERVICE_USER}" "${VENV_DIR}/bin/pip" install -r "${INSTALL_DIR}/requirements.txt" -r "${PLATFORM_REQS}"
|
||||
|
||||
if [[ -f /etc/nv_tegra_release ]]; then
|
||||
PLATFORM_SMOKE="import tensorrt, pycuda.driver
|
||||
print('tensorrt + pycuda ok')"
|
||||
else
|
||||
PLATFORM_SMOKE="from rknnlite.api import RKNNLite
|
||||
print('rknnlite ok')"
|
||||
fi
|
||||
sudo -u "${SERVICE_USER}" PYTHONNOUSERSITE=1 "${VENV_DIR}/bin/python" -c "
|
||||
from rknnlite.api import RKNNLite
|
||||
import cv2
|
||||
import flask
|
||||
import dotenv
|
||||
import openpyxl
|
||||
print('venv ok | rknn + opencv + flask + dotenv + openpyxl')
|
||||
${PLATFORM_SMOKE}
|
||||
print('venv ok | opencv + flask + dotenv + openpyxl + backend')
|
||||
"
|
||||
|
||||
echo ""
|
||||
|
||||
Reference in new issue
Block a user