307 lines
11 KiB
Python
307 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Jetson Orin Nano - marker SEGMENTATION tracking with TensorRT.
|
|
|
|
Model: marker_seg_best.pt (class 0 -> marker)
|
|
|
|
Pipeline: .pt -> .onnx -> .engine (TensorRT) -> real-time tracking on GPU.
|
|
If marker_seg_best.engine exists next to marker_seg_best.pt it is loaded
|
|
automatically, otherwise the .pt file is used.
|
|
|
|
IMPORTANT: a TensorRT engine has a FIXED input size. Use the same --imgsz for
|
|
export and for inference (e.g. 416 or 640).
|
|
|
|
USAGE
|
|
-----
|
|
1) One-time export (.pt -> .onnx -> .engine, FP16):
|
|
python3 marker_segmentation.py --export-tensorrt --imgsz 416
|
|
|
|
(ONNX only, no engine:)
|
|
python3 marker_segmentation.py --export-onnx --imgsz 416
|
|
|
|
2) Live tracking, USB camera:
|
|
python3 marker_segmentation.py --source 0 --imgsz 416
|
|
|
|
CSI camera:
|
|
python3 marker_segmentation.py --source csi --imgsz 416
|
|
|
|
Video file + save:
|
|
python3 marker_segmentation.py --source my_video.mp4 --imgsz 416 --save out.mp4
|
|
|
|
BoT-SORT instead of ByteTrack:
|
|
python3 marker_segmentation.py --source 0 --imgsz 416 --tracker botsort.yaml
|
|
|
|
Headless over SSH:
|
|
python3 marker_segmentation.py --source 0 --imgsz 416 --no-display
|
|
|
|
Debug (print what the model returned each frame):
|
|
python3 marker_segmentation.py --source 0 --imgsz 416 --debug
|
|
"""
|
|
|
|
import argparse
|
|
import os
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import cv2
|
|
import numpy as np
|
|
from ultralytics import YOLO
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Config
|
|
# ---------------------------------------------------------------------------
|
|
# Folder of this script (marker_seg_best.pt lives next to it).
|
|
MODEL_DIR = Path(os.path.dirname(os.path.abspath(__file__)))
|
|
SEG_WEIGHTS = MODEL_DIR / "marker_seg_best.pt"
|
|
|
|
CLASS_NAME = "marker"
|
|
BOX_COLOR = (0, 255, 0) # BGR
|
|
MASK_ALPHA = 0.4
|
|
MIN_MASK_AREA_FRAC = 0.0015 # ignore tiny/far masks
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Export helpers (run once)
|
|
# ---------------------------------------------------------------------------
|
|
def export_onnx(imgsz: int) -> None:
|
|
if not SEG_WEIGHTS.exists():
|
|
print(f"Weights not found at: {SEG_WEIGHTS}")
|
|
return
|
|
print(f"Exporting {SEG_WEIGHTS.name} to ONNX (imgsz={imgsz}) ...")
|
|
out = YOLO(str(SEG_WEIGHTS)).export(format="onnx", imgsz=imgsz, opset=12, simplify=True)
|
|
print(f"Done: {out}")
|
|
|
|
|
|
def export_tensorrt(imgsz: int, quantize: int) -> None:
|
|
if not SEG_WEIGHTS.exists():
|
|
print(f"Weights not found at: {SEG_WEIGHTS}")
|
|
return
|
|
half = quantize == 16
|
|
int8 = quantize == 8
|
|
print(f"Exporting {SEG_WEIGHTS.name} to TensorRT (.engine), imgsz={imgsz} "
|
|
f"half={half} int8={int8} ...")
|
|
# Ultralytics builds the .onnx first and then the .engine, so both files
|
|
# appear next to the .pt file.
|
|
out = YOLO(str(SEG_WEIGHTS)).export(
|
|
format="engine", imgsz=imgsz, half=half, int8=int8, device=0)
|
|
print(f"Done: {out}")
|
|
print("Re-run without --export-tensorrt to track using the .engine file.")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Camera / source handling
|
|
# ---------------------------------------------------------------------------
|
|
def build_csi_pipeline(width=1280, height=720, fps=30):
|
|
return (
|
|
f"nvarguscamerasrc ! video/x-raw(memory:NVMM), width={width}, height={height}, "
|
|
f"format=NV12, framerate={fps}/1 ! nvvidconv flip-method=0 ! "
|
|
f"video/x-raw, width={width}, height={height}, format=BGRx ! "
|
|
f"videoconvert ! video/x-raw, format=BGR ! appsink drop=1"
|
|
)
|
|
|
|
|
|
def open_capture(source: str):
|
|
if source == "csi":
|
|
return cv2.VideoCapture(build_csi_pipeline(), cv2.CAP_GSTREAMER)
|
|
if source.isdigit():
|
|
return cv2.VideoCapture(int(source), cv2.CAP_V4L2)
|
|
return cv2.VideoCapture(source)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Drawing
|
|
# ---------------------------------------------------------------------------
|
|
def draw_all(frame, detections):
|
|
"""Draw all masks with ONE overlay blend (faster than one per detection)."""
|
|
if not detections:
|
|
return frame
|
|
|
|
overlay = frame.copy()
|
|
for mask_poly, _, _, _ in detections:
|
|
if len(mask_poly) >= 3:
|
|
cv2.fillPoly(overlay, [mask_poly.astype(np.int32)], BOX_COLOR)
|
|
cv2.addWeighted(overlay, MASK_ALPHA, frame, 1 - MASK_ALPHA, 0, dst=frame)
|
|
|
|
for mask_poly, box, tid, conf in detections:
|
|
if len(mask_poly) >= 3:
|
|
cv2.polylines(frame, [mask_poly.astype(np.int32)], True, BOX_COLOR, 2)
|
|
label = f"ID:{tid} {CLASS_NAME} {conf:.2f}"
|
|
x1, y1, _, _ = map(int, box)
|
|
(tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
|
|
top = max(y1 - th - 8, 0)
|
|
cv2.rectangle(frame, (x1, top), (x1 + tw + 4, top + th + 8), BOX_COLOR, -1)
|
|
cv2.putText(frame, label, (x1 + 2, top + th + 2),
|
|
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1, cv2.LINE_AA)
|
|
return frame
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Tracking on one frame
|
|
# ---------------------------------------------------------------------------
|
|
def run_seg_track(model, frame, args):
|
|
"""Return list of (mask_poly_xy, box_xyxy, track_id, conf)."""
|
|
frame_area = frame.shape[0] * frame.shape[1]
|
|
|
|
results = model.track(
|
|
source=frame,
|
|
conf=args.conf,
|
|
iou=args.iou,
|
|
imgsz=args.imgsz,
|
|
device=args.device,
|
|
tracker=args.tracker,
|
|
persist=True,
|
|
verbose=False,
|
|
)
|
|
|
|
detections = []
|
|
if not results:
|
|
if args.debug:
|
|
print("no results returned")
|
|
return detections
|
|
|
|
r = results[0]
|
|
if r.boxes is None or len(r.boxes) == 0:
|
|
if args.debug:
|
|
print(f"0 raw detections above conf={args.conf}")
|
|
return detections
|
|
if r.boxes.id is None:
|
|
if args.debug:
|
|
print(f"{len(r.boxes)} raw detections, tracker assigned no ids yet")
|
|
return detections
|
|
if r.masks is None:
|
|
if args.debug:
|
|
print(f"{len(r.boxes)} raw detections, but no masks returned "
|
|
"(is this a -seg model/engine?)")
|
|
return detections
|
|
|
|
boxes = r.boxes.xyxy.cpu().numpy()
|
|
ids = r.boxes.id.cpu().numpy().astype(int)
|
|
confs = r.boxes.conf.cpu().numpy()
|
|
mask_polys = r.masks.xy # list of (N,2) polygons in original frame pixels
|
|
|
|
for box, tid, conf, poly in zip(boxes, ids, confs, mask_polys):
|
|
area = cv2.contourArea(poly.astype(np.int32)) if len(poly) >= 3 else 0.0
|
|
if area / frame_area < MIN_MASK_AREA_FRAC:
|
|
if args.debug:
|
|
print(f"dropped conf={conf:.2f}: mask area {area / frame_area:.5f} "
|
|
f"< {MIN_MASK_AREA_FRAC}")
|
|
continue
|
|
detections.append((poly, box, tid, float(conf)))
|
|
return detections
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Main
|
|
# ---------------------------------------------------------------------------
|
|
def parse_args():
|
|
p = argparse.ArgumentParser(description="Marker segmentation tracking (Jetson, TensorRT)")
|
|
p.add_argument("--source", type=str, default="0",
|
|
help="'0'/'1' USB camera index, 'csi', or a video file path.")
|
|
p.add_argument("--weights", type=str, default=None,
|
|
help="Override weights (.pt or .engine). Default: marker_seg_best.engine "
|
|
"if it exists, else marker_seg_best.pt.")
|
|
p.add_argument("--imgsz", type=int, default=416,
|
|
help="Must match the size used for export when using the engine.")
|
|
p.add_argument("--conf", type=float, default=0.40)
|
|
p.add_argument("--iou", type=float, default=0.50)
|
|
p.add_argument("--device", type=str, default="0", help="'0' = Jetson GPU, 'cpu' = CPU.")
|
|
p.add_argument("--tracker", type=str, default="bytetrack.yaml",
|
|
help="'bytetrack.yaml' or 'botsort.yaml'.")
|
|
p.add_argument("--quantize", type=int, default=16, choices=[8, 16, 32],
|
|
help="Export precision: 16 = FP16 (recommended), 32 = FP32, 8 = INT8.")
|
|
p.add_argument("--save", type=str, default=None, help="Output video path.")
|
|
p.add_argument("--no-display", action="store_true", help="No preview window (headless).")
|
|
p.add_argument("--debug", action="store_true", help="Print raw detection info each frame.")
|
|
p.add_argument("--export-onnx", action="store_true",
|
|
help="One-time: export .pt to .onnx, then exit.")
|
|
p.add_argument("--export-tensorrt", action="store_true",
|
|
help="One-time: export .pt to .onnx + .engine, then exit.")
|
|
return p.parse_args()
|
|
|
|
|
|
def main():
|
|
args = parse_args()
|
|
|
|
if args.export_onnx:
|
|
export_onnx(args.imgsz)
|
|
return
|
|
if args.export_tensorrt:
|
|
export_tensorrt(args.imgsz, args.quantize)
|
|
return
|
|
|
|
weights_path = Path(args.weights) if args.weights else SEG_WEIGHTS
|
|
if not args.weights:
|
|
engine_path = SEG_WEIGHTS.with_suffix(".engine")
|
|
if engine_path.exists():
|
|
print(f"Found TensorRT engine at {engine_path}, using it instead of .pt.")
|
|
weights_path = engine_path
|
|
if not weights_path.exists():
|
|
raise FileNotFoundError(f"Weights not found at: {weights_path}")
|
|
|
|
print(f"Loading marker segmentation model from {weights_path} ...")
|
|
model = YOLO(str(weights_path), task="segment")
|
|
print("Model loaded.")
|
|
|
|
try:
|
|
import torch
|
|
cuda_ok = torch.cuda.is_available()
|
|
print(f"torch.cuda.is_available() = {cuda_ok}"
|
|
+ (f" ({torch.cuda.get_device_name(0)})" if cuda_ok else ""))
|
|
if args.device != "cpu" and not cuda_ok:
|
|
print("WARNING: GPU requested but CUDA not available to this torch build.")
|
|
except Exception as e:
|
|
print(f"Could not check CUDA availability: {e}")
|
|
|
|
print("Warming up model...")
|
|
t0 = time.time()
|
|
dummy = np.zeros((args.imgsz, args.imgsz, 3), dtype="uint8")
|
|
model.predict(source=dummy, conf=args.conf, imgsz=args.imgsz,
|
|
device=args.device, verbose=False)
|
|
print(f"Warmup done in {time.time() - t0:.2f}s.")
|
|
|
|
cap = open_capture(args.source)
|
|
if not cap.isOpened():
|
|
raise RuntimeError(f"Could not open source: {args.source}")
|
|
|
|
writer = None
|
|
if args.save:
|
|
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
|
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) or 1280
|
|
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) or 720
|
|
fps_out = cap.get(cv2.CAP_PROP_FPS) or 20
|
|
writer = cv2.VideoWriter(args.save, fourcc, fps_out, (w, h))
|
|
|
|
print("Starting segmentation tracking. Press 'q' to quit.")
|
|
prev_t = time.time()
|
|
|
|
while True:
|
|
ok, frame = cap.read()
|
|
if not ok:
|
|
print("End of stream / camera read failed.")
|
|
break
|
|
|
|
detections = run_seg_track(model, frame, args)
|
|
frame = draw_all(frame, detections)
|
|
|
|
now = time.time()
|
|
fps = 1.0 / max(now - prev_t, 1e-6)
|
|
prev_t = now
|
|
cv2.putText(frame, f"FPS: {fps:.1f}", (10, 25),
|
|
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2, cv2.LINE_AA)
|
|
|
|
if writer is not None:
|
|
writer.write(frame)
|
|
if not args.no_display:
|
|
cv2.imshow("Marker Segmentation Tracking", frame)
|
|
if cv2.waitKey(1) & 0xFF == ord("q"):
|
|
break
|
|
|
|
cap.release()
|
|
if writer is not None:
|
|
writer.release()
|
|
cv2.destroyAllWindows()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|