410 lines
13 KiB
Python
Executable File
410 lines
13 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Convert an Ultralytics YOLO .pt model to an INT8 RKNN model for RK3588.
|
|
|
|
Exports the raw multi-branch YOLO head (per-scale box DFL + class logits, plus
|
|
angle logits for OBB) without DFL decode or sigmoid so the output matches
|
|
``counter_live_rknn.RKNNYOLO._decode_multibranch``.
|
|
"""
|
|
|
|
import argparse
|
|
import inspect
|
|
import os
|
|
import sys
|
|
import time
|
|
import types
|
|
from pathlib import Path
|
|
|
|
import cv2
|
|
import numpy as np
|
|
import onnx
|
|
import torch
|
|
from dotenv import dotenv_values
|
|
from rknn.api import RKNN
|
|
from ultralytics import YOLO
|
|
|
|
|
|
IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp"}
|
|
|
|
|
|
def letterbox_image(frame: np.ndarray, imgsz: int) -> np.ndarray:
|
|
"""Resize and pad frame to square (imgsz, imgsz, 3) BGR matching RKNNYOLO._preprocess."""
|
|
h0, w0 = frame.shape[:2]
|
|
scale = min(imgsz / h0, imgsz / w0)
|
|
nh, nw = int(h0 * scale), int(w0 * scale)
|
|
resized = cv2.resize(frame, (nw, nh), interpolation=cv2.INTER_LINEAR)
|
|
|
|
canvas = np.full((imgsz, imgsz, 3), 114, dtype=np.uint8)
|
|
dy = (imgsz - nh) // 2
|
|
dx = (imgsz - nw) // 2
|
|
canvas[dy : dy + nh, dx : dx + nw] = resized
|
|
return canvas
|
|
|
|
|
|
def load_env_defaults(env_file: Path) -> tuple[str | None, str]:
|
|
"""Read SOURCE and OPENCV_FFMPEG_CAPTURE_OPTIONS from an env file."""
|
|
if not env_file.is_file():
|
|
return None, "rtsp_transport;tcp|fflags;nobuffer|flags;low_delay"
|
|
cfg = dotenv_values(env_file)
|
|
source = (cfg.get("SOURCE") or "").strip() or None
|
|
ffmpeg_opts = (
|
|
cfg.get("OPENCV_FFMPEG_CAPTURE_OPTIONS")
|
|
or "rtsp_transport;tcp|fflags;nobuffer|flags;low_delay"
|
|
).strip()
|
|
return source, ffmpeg_opts
|
|
|
|
|
|
def _collect_existing_images(calib_dir: Path) -> list[Path]:
|
|
if not calib_dir.is_dir():
|
|
return []
|
|
return sorted(
|
|
p
|
|
for p in calib_dir.iterdir()
|
|
if p.is_file() and p.suffix.lower() in IMAGE_EXTS
|
|
)
|
|
|
|
|
|
def _capture_rtsp_frames(
|
|
source: str,
|
|
ffmpeg_opts: str,
|
|
calib_dir: Path,
|
|
imgsz: int,
|
|
target_count: int,
|
|
interval_sec: float,
|
|
) -> list[Path]:
|
|
"""Capture letterboxed calibration frames from an RTSP stream or video file."""
|
|
calib_dir.mkdir(parents=True, exist_ok=True)
|
|
if source.lower().startswith(("rtsp://", "http://")):
|
|
os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = ffmpeg_opts
|
|
|
|
print(f"Capturing {target_count} calibration frames from: {source}")
|
|
cap = cv2.VideoCapture(source, cv2.CAP_FFMPEG)
|
|
if not cap.isOpened():
|
|
raise RuntimeError(f"Failed to open video/RTSP source: {source}")
|
|
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
|
|
|
|
saved: list[Path] = []
|
|
try:
|
|
for _ in range(10):
|
|
cap.read()
|
|
|
|
existing = _collect_existing_images(calib_dir)
|
|
start_idx = len(existing)
|
|
consecutive_failures = 0
|
|
|
|
while len(saved) + len(existing) < target_count:
|
|
ok, frame = cap.read()
|
|
if not ok or frame is None:
|
|
consecutive_failures += 1
|
|
if consecutive_failures >= 30:
|
|
break
|
|
time.sleep(0.05)
|
|
continue
|
|
consecutive_failures = 0
|
|
|
|
lb = letterbox_image(frame, imgsz)
|
|
out_path = calib_dir / f"calib_{start_idx + len(saved):04d}.jpg"
|
|
cv2.imwrite(str(out_path), lb, [cv2.IMWRITE_JPEG_QUALITY, 95])
|
|
saved.append(out_path)
|
|
|
|
# Drain buffered frames during the interval so each sample is fresh.
|
|
if interval_sec > 0 and len(saved) + len(existing) < target_count:
|
|
deadline = time.monotonic() + interval_sec
|
|
while time.monotonic() < deadline:
|
|
cap.grab()
|
|
time.sleep(0.01)
|
|
finally:
|
|
cap.release()
|
|
|
|
all_imgs = _collect_existing_images(calib_dir)
|
|
if len(all_imgs) < 10:
|
|
raise RuntimeError(
|
|
f"Captured only {len(all_imgs)} calibration frames (minimum 10 required) from {source}"
|
|
)
|
|
print(f"Prepared {len(all_imgs)} calibration images in {calib_dir}")
|
|
return all_imgs
|
|
|
|
|
|
def prepare_calibration_dataset(
|
|
calib_dir: Path,
|
|
imgsz: int,
|
|
target_count: int,
|
|
interval_sec: float,
|
|
rtsp_source: str | None,
|
|
env_file: Path,
|
|
) -> tuple[Path, int]:
|
|
"""Ensure calibration directory has letterboxed images and write dataset.txt."""
|
|
existing = _collect_existing_images(calib_dir)
|
|
if len(existing) < target_count:
|
|
env_source, ffmpeg_opts = load_env_defaults(env_file)
|
|
source = rtsp_source or env_source
|
|
if not source:
|
|
raise RuntimeError(
|
|
f"Calibration dir {calib_dir} has {len(existing)}/{target_count} images "
|
|
"and no --rtsp or SOURCE in .env was provided."
|
|
)
|
|
existing = _capture_rtsp_frames(
|
|
source=source,
|
|
ffmpeg_opts=ffmpeg_opts,
|
|
calib_dir=calib_dir,
|
|
imgsz=imgsz,
|
|
target_count=target_count,
|
|
interval_sec=interval_sec,
|
|
)
|
|
else:
|
|
print(f"Using {len(existing)} existing calibration images in {calib_dir}")
|
|
|
|
# Guarantee every image fed to RKNN matches (imgsz, imgsz) via letterboxing.
|
|
lb_dir = calib_dir / f"_lb_{imgsz}"
|
|
dataset_paths: list[Path] = []
|
|
for idx, img_path in enumerate(existing[:target_count]):
|
|
img = cv2.imread(str(img_path))
|
|
if img is None:
|
|
continue
|
|
if img.shape[0] == imgsz and img.shape[1] == imgsz:
|
|
dataset_paths.append(img_path.resolve())
|
|
else:
|
|
lb_dir.mkdir(parents=True, exist_ok=True)
|
|
lb_path = lb_dir / f"lb_{idx:04d}.jpg"
|
|
cv2.imwrite(
|
|
str(lb_path),
|
|
letterbox_image(img, imgsz),
|
|
[cv2.IMWRITE_JPEG_QUALITY, 95],
|
|
)
|
|
dataset_paths.append(lb_path.resolve())
|
|
|
|
if len(dataset_paths) < 10:
|
|
raise RuntimeError(
|
|
f"Only {len(dataset_paths)} readable calibration images in {calib_dir}"
|
|
)
|
|
|
|
dataset_txt = calib_dir / "dataset.txt"
|
|
dataset_txt.write_text("\n".join(str(p) for p in dataset_paths) + "\n", encoding="utf-8")
|
|
return dataset_txt, len(dataset_paths)
|
|
|
|
|
|
def _multibranch_forward(self, x):
|
|
"""Return raw per-scale Detect/OBB head tensors without DFL decode or sigmoid."""
|
|
outputs = []
|
|
has_obb = hasattr(self, "cv4")
|
|
for i in range(self.nl):
|
|
outputs.append(self.cv2[i](x[i]))
|
|
outputs.append(self.cv3[i](x[i]))
|
|
if has_obb:
|
|
outputs.append(self.cv4[i](x[i]))
|
|
return tuple(outputs)
|
|
|
|
|
|
def export_multibranch_onnx(
|
|
pt_path: Path, onnx_path: Path, imgsz: int, opset: int
|
|
) -> tuple[dict, list[tuple[str, tuple[int, ...]]]]:
|
|
"""Export YOLO .pt model to multi-branch ONNX matching RKNNYOLO._decode_multibranch."""
|
|
yolo = YOLO(str(pt_path))
|
|
class_names = dict(yolo.names)
|
|
|
|
pt_model = yolo.model.eval().cpu().float()
|
|
if hasattr(pt_model, "fuse"):
|
|
pt_model.fuse()
|
|
|
|
head = pt_model.model[-1]
|
|
if not (hasattr(head, "cv2") and hasattr(head, "cv3") and hasattr(head, "nl")):
|
|
raise RuntimeError(
|
|
f"Unsupported model head {type(head).__name__}: expected cv2, cv3, and nl attributes."
|
|
)
|
|
|
|
has_obb = hasattr(head, "cv4")
|
|
head.forward = types.MethodType(_multibranch_forward, head)
|
|
|
|
output_names: list[str] = []
|
|
for i in range(head.nl):
|
|
output_names.extend([f"box_{i}", f"cls_{i}"])
|
|
if has_obb:
|
|
output_names.append(f"angle_{i}")
|
|
|
|
dummy = torch.zeros(1, 3, imgsz, imgsz, dtype=torch.float32)
|
|
with torch.no_grad():
|
|
sample_outs = pt_model(dummy)
|
|
|
|
export_kwargs = {
|
|
"opset_version": opset,
|
|
"input_names": ["images"],
|
|
"output_names": output_names,
|
|
"do_constant_folding": True,
|
|
}
|
|
if "dynamo" in inspect.signature(torch.onnx.export).parameters:
|
|
export_kwargs["dynamo"] = False
|
|
|
|
torch.onnx.export(pt_model, dummy, str(onnx_path), **export_kwargs)
|
|
|
|
onnx_model = onnx.load(str(onnx_path))
|
|
onnx.checker.check_model(onnx_model)
|
|
|
|
out_shapes = [(name, tuple(tensor.shape)) for name, tensor in zip(output_names, sample_outs)]
|
|
print(f"Exported ONNX: {onnx_path} (opset={opset}, outputs={len(out_shapes)})")
|
|
for name, shape in out_shapes:
|
|
print(f" {name}: {shape}")
|
|
|
|
return class_names, out_shapes
|
|
|
|
|
|
def build_rknn(
|
|
onnx_path: Path,
|
|
rknn_path: Path,
|
|
target: str,
|
|
quant: bool,
|
|
quant_dtype: str,
|
|
dataset_txt: Path | None,
|
|
) -> None:
|
|
"""Compile ONNX model to RKNN (INT8 quantized when quant=True)."""
|
|
rknn = RKNN(verbose=False)
|
|
try:
|
|
ret = rknn.config(
|
|
mean_values=[[0, 0, 0]],
|
|
std_values=[[255, 255, 255]],
|
|
target_platform=target,
|
|
quantized_dtype=quant_dtype,
|
|
quantized_algorithm="normal",
|
|
quantized_method="channel",
|
|
optimization_level=3,
|
|
)
|
|
if ret != 0:
|
|
raise RuntimeError(f"rknn.config failed with code {ret}")
|
|
|
|
ret = rknn.load_onnx(model=str(onnx_path))
|
|
if ret != 0:
|
|
raise RuntimeError(f"rknn.load_onnx failed with code {ret}")
|
|
|
|
ret = rknn.build(
|
|
do_quantization=quant,
|
|
dataset=str(dataset_txt) if (quant and dataset_txt is not None) else None,
|
|
)
|
|
if ret != 0:
|
|
raise RuntimeError(f"rknn.build failed with code {ret}")
|
|
|
|
rknn_path.parent.mkdir(parents=True, exist_ok=True)
|
|
ret = rknn.export_rknn(str(rknn_path))
|
|
if ret != 0:
|
|
raise RuntimeError(f"rknn.export_rknn failed with code {ret}")
|
|
finally:
|
|
rknn.release()
|
|
|
|
|
|
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
|
parser = argparse.ArgumentParser(
|
|
description="Convert Ultralytics YOLO .pt to INT8 .rknn for RK3588"
|
|
)
|
|
parser.add_argument("pt_path", type=Path, help="Input Ultralytics .pt model path")
|
|
parser.add_argument(
|
|
"-o",
|
|
"--output",
|
|
type=Path,
|
|
default=None,
|
|
help="Output .rknn path (default: <pt_path stem>.rknn)",
|
|
)
|
|
parser.add_argument("--imgsz", type=int, default=480, help="Square input size (default: 480)")
|
|
parser.add_argument("--target", default="rk3588", help="RKNN target platform (default: rk3588)")
|
|
parser.add_argument(
|
|
"--quant",
|
|
action=argparse.BooleanOptionalAction,
|
|
default=True,
|
|
help="Enable INT8 quantization (default: True)",
|
|
)
|
|
parser.add_argument(
|
|
"--quant-dtype",
|
|
default="w8a8",
|
|
help="RKNN quantized_dtype (default: w8a8)",
|
|
)
|
|
parser.add_argument(
|
|
"--calib-dir",
|
|
type=Path,
|
|
default=None,
|
|
help="Calibration image directory (default: /opt/models/calib_images_<imgsz>)",
|
|
)
|
|
parser.add_argument(
|
|
"--rtsp",
|
|
default=None,
|
|
help="RTSP URL or video file to capture calibration frames from (default: SOURCE from .env)",
|
|
)
|
|
parser.add_argument(
|
|
"--env-file",
|
|
type=Path,
|
|
default=Path("/opt/feedmill/.env"),
|
|
help="Env file for default SOURCE and FFMPEG options (default: /opt/feedmill/.env)",
|
|
)
|
|
parser.add_argument(
|
|
"--calib-frames",
|
|
type=int,
|
|
default=50,
|
|
help="Number of calibration frames to collect (default: 50)",
|
|
)
|
|
parser.add_argument(
|
|
"--calib-interval",
|
|
type=float,
|
|
default=0.3,
|
|
help="Seconds between captured calibration frames (default: 0.3)",
|
|
)
|
|
parser.add_argument("--opset", type=int, default=12, help="ONNX opset version (default: 12)")
|
|
parser.add_argument(
|
|
"--keep-onnx",
|
|
action="store_true",
|
|
help="Keep intermediate .onnx file alongside output .rknn",
|
|
)
|
|
return parser.parse_args(argv)
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
args = parse_args(argv)
|
|
pt_path = args.pt_path.resolve()
|
|
if not pt_path.is_file():
|
|
print(f"ERROR: Input .pt model not found: {pt_path}", file=sys.stderr)
|
|
return 1
|
|
|
|
rknn_path = (args.output or pt_path.with_suffix(".rknn")).resolve()
|
|
onnx_path = rknn_path.with_suffix(".onnx")
|
|
calib_dir = (args.calib_dir or Path(f"/opt/models/calib_images_{args.imgsz}")).resolve()
|
|
|
|
dataset_txt = None
|
|
calib_count = 0
|
|
if args.quant:
|
|
dataset_txt, calib_count = prepare_calibration_dataset(
|
|
calib_dir=calib_dir,
|
|
imgsz=args.imgsz,
|
|
target_count=args.calib_frames,
|
|
interval_sec=args.calib_interval,
|
|
rtsp_source=args.rtsp,
|
|
env_file=args.env_file,
|
|
)
|
|
|
|
class_names, _ = export_multibranch_onnx(
|
|
pt_path=pt_path,
|
|
onnx_path=onnx_path,
|
|
imgsz=args.imgsz,
|
|
opset=args.opset,
|
|
)
|
|
|
|
try:
|
|
build_rknn(
|
|
onnx_path=onnx_path,
|
|
rknn_path=rknn_path,
|
|
target=args.target,
|
|
quant=args.quant,
|
|
quant_dtype=args.quant_dtype,
|
|
dataset_txt=dataset_txt,
|
|
)
|
|
finally:
|
|
if not args.keep_onnx and onnx_path.exists():
|
|
onnx_path.unlink()
|
|
|
|
size_mb = rknn_path.stat().st_size / (1024 * 1024)
|
|
quant_desc = f"INT8 ({args.quant_dtype}, {calib_count} calib frames)" if args.quant else "FP16 (no quant)"
|
|
print("\nConversion complete:")
|
|
print(f" RKNN model : {rknn_path} ({size_mb:.2f} MB)")
|
|
print(f" Input size : {args.imgsz}x{args.imgsz}")
|
|
print(f" Target : {args.target}")
|
|
print(f" Precision : {quant_desc}")
|
|
print(f" Classes : {class_names}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|