initial project upload
This commit is contained in:
@@ -0,0 +1,218 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Jetson Orin Nano - marker tracking (ByteTrack / BoT-SORT) with TensorRT engine.
|
||||
|
||||
Works like marker1.py: if marker_best.engine exists next to marker_best.pt it is
|
||||
loaded automatically (much faster). Otherwise it falls back to the .pt file.
|
||||
|
||||
IMPORTANT: a TensorRT engine has a FIXED input size. Use the same --imgsz here
|
||||
that you used for --export-tensorrt in marker1.py (416 in your case).
|
||||
|
||||
USAGE
|
||||
-----
|
||||
Live USB camera, using the engine:
|
||||
python3 marker_tracking.py --source 0 --imgsz 416
|
||||
|
||||
CSI camera:
|
||||
python3 marker_tracking.py --source csi --imgsz 416
|
||||
|
||||
Video file, save output:
|
||||
python3 marker_tracking.py --source my_video.mp4 --imgsz 416 --save out.mp4
|
||||
|
||||
Use BoT-SORT instead of ByteTrack:
|
||||
python3 marker_tracking.py --source 0 --imgsz 416 --tracker botsort.yaml
|
||||
|
||||
Headless over SSH:
|
||||
python3 marker_tracking.py --source 0 --imgsz 416 --no-display
|
||||
|
||||
Force a specific weights file (.pt or .engine):
|
||||
python3 marker_tracking.py --weights /path/to/marker_best.engine --imgsz 416
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
from ultralytics import YOLO
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Config
|
||||
# ---------------------------------------------------------------------------
|
||||
MODEL_DIR = Path("/home/jetson/yolo_object_detection/yolo26_model")
|
||||
MARKER_WEIGHTS = MODEL_DIR / "marker_best.pt"
|
||||
|
||||
CLASS_NAME = "marker"
|
||||
BOX_COLOR = (0, 255, 0) # BGR
|
||||
|
||||
# Ignore boxes smaller than this fraction of the frame area (tiny/unreliable)
|
||||
MIN_BOX_AREA_FRAC = 0.0015
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Camera / source handling (same as marker1.py)
|
||||
# ---------------------------------------------------------------------------
|
||||
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_box(frame, box, track_id, conf):
|
||||
x1, y1, x2, y2 = map(int, box)
|
||||
label = f"ID:{track_id} {CLASS_NAME} {conf:.2f}"
|
||||
cv2.rectangle(frame, (x1, y1), (x2, y2), BOX_COLOR, 2)
|
||||
(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)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tracking on one frame
|
||||
# ---------------------------------------------------------------------------
|
||||
def run_model_track(model, frame, args):
|
||||
"""Return list of (box_xyxy, track_id, conf)."""
|
||||
frame_h, frame_w = frame.shape[:2]
|
||||
frame_area = frame_h * frame_w
|
||||
|
||||
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:
|
||||
return detections
|
||||
|
||||
r = results[0]
|
||||
if r.boxes is None or r.boxes.id is None:
|
||||
return detections
|
||||
|
||||
boxes = r.boxes.xyxy.cpu().numpy()
|
||||
ids = r.boxes.id.cpu().numpy().astype(int)
|
||||
confs = r.boxes.conf.cpu().numpy()
|
||||
|
||||
for box, tid, conf in zip(boxes, ids, confs):
|
||||
x1, y1, x2, y2 = box
|
||||
box_area = max(0.0, x2 - x1) * max(0.0, y2 - y1)
|
||||
if box_area / frame_area < MIN_BOX_AREA_FRAC:
|
||||
continue
|
||||
detections.append((box, tid, float(conf)))
|
||||
return detections
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Main
|
||||
# ---------------------------------------------------------------------------
|
||||
def parse_args():
|
||||
p = argparse.ArgumentParser(description="Marker tracking for Jetson Orin Nano (TensorRT)")
|
||||
p.add_argument("--source", type=str, default="0",
|
||||
help="'0'/'1' USB camera index, 'csi' for CSI camera, or a video file path.")
|
||||
p.add_argument("--weights", type=str, default=None,
|
||||
help="Override weights path (.pt or .engine). Default: marker_best.engine "
|
||||
"if it exists, else marker_best.pt.")
|
||||
p.add_argument("--imgsz", type=int, default=416,
|
||||
help="Must match the size used when exporting the engine (416).")
|
||||
p.add_argument("--conf", type=float, default=0.40, help="Confidence threshold.")
|
||||
p.add_argument("--iou", type=float, default=0.50, help="NMS IoU threshold.")
|
||||
p.add_argument("--device", type=str, default="0", help="'0' for Jetson GPU, 'cpu' for CPU.")
|
||||
p.add_argument("--tracker", type=str, default="bytetrack.yaml",
|
||||
help="'bytetrack.yaml' or 'botsort.yaml'.")
|
||||
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).")
|
||||
return p.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
args = parse_args()
|
||||
|
||||
# Pick weights: engine preferred, same logic as marker1.py
|
||||
weights_path = Path(args.weights) if args.weights else MARKER_WEIGHTS
|
||||
if not args.weights:
|
||||
engine_path = MARKER_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"Marker weights not found at: {weights_path}")
|
||||
|
||||
print(f"Loading marker model from {weights_path} ...")
|
||||
model = YOLO(str(weights_path), task="detect")
|
||||
print("Model loaded.")
|
||||
|
||||
# Warm-up (first call pays CUDA / TensorRT init cost)
|
||||
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 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
|
||||
|
||||
for box, tid, conf in run_model_track(model, frame, args):
|
||||
draw_box(frame, box, tid, conf)
|
||||
|
||||
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 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()
|
||||
Reference in New Issue
Block a user