Files
marker_detection/marker_detection.py
2026-11-02 14:43:08 +05:30

261 lines
11 KiB
Python

#!/usr/bin/env python3
import argparse
import time
from pathlib import Path
import cv2
from ultralytics import YOLO
# ---------------------------------------------------------------------------
# Config — edit if your folder layout or class ids differ
# ---------------------------------------------------------------------------
MODEL_DIR = Path("/home/jetson/projects_2026/Marker/Marker_detection/models")
MARKER_WEIGHTS = MODEL_DIR / "marker_best.pt"
MARKER_NAMES = {0: "Marker"}
MARKER_COLOR = (0, 200, 0) # BGR
IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp"}
# ---------------------------------------------------------------------------
# TensorRT export helper (optional, run once)
# ---------------------------------------------------------------------------
def export_tensorrt(imgsz: int, quantize: int) -> None:
if not MARKER_WEIGHTS.exists():
print(f"Marker weights not found at: {MARKER_WEIGHTS}")
return
# Ultralytics export doesn't take a 'quantize' kwarg. Map our --quantize
# flag (8/16/32) onto the real export flags: half=True for FP16,
# int8=True for INT8. 32 means "no extra quantization" (FP32 engine).
half = quantize == 16
int8 = quantize == 8
print(f"Exporting {MARKER_WEIGHTS.name} to TensorRT (.engine), "
f"half={half} int8={int8} ...")
YOLO(str(MARKER_WEIGHTS)).export(format="engine", imgsz=imgsz, half=half, int8=int8, device=0)
print("Done. Re-run without --export-tensorrt to use the .engine file "
"(point --weights at the .engine path, or rename it over the .pt path).")
# ---------------------------------------------------------------------------
# Detection + drawing
# ---------------------------------------------------------------------------
def draw_detections(frame, result):
for box in result.boxes:
x1, y1, x2, y2 = map(int, box.xyxy[0])
cls_id = int(box.cls[0])
conf = float(box.conf[0])
label = f"{MARKER_NAMES.get(cls_id, cls_id)} {conf:.2f}"
cv2.rectangle(frame, (x1, y1), (x2, y2), MARKER_COLOR, 2)
cv2.putText(frame, label, (x1, max(y1 - 6, 0)),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, MARKER_COLOR, 2)
def run_on_frame(frame, model, args):
# In debug mode, run at a very low conf so we can see everything the
# model considered, then print+draw only what's actually there.
conf = 0.05 if args.debug else args.conf
# 'quantize' is not a real predict() kwarg (it silently did nothing
# before). The correct inference-time flag is 'half'.
use_half = args.quantize == 16 and args.device != "cpu"
result = model.predict(
source=frame, conf=conf, imgsz=args.imgsz,
device=args.device, half=use_half, verbose=False)[0]
if args.debug:
if len(result.boxes) == 0:
print(" (no candidate boxes at all this frame)")
for box in result.boxes:
cls_id = int(box.cls[0])
c = float(box.conf[0])
flag = "OK " if c >= args.conf else "low"
print(f" [{flag}] {MARKER_NAMES.get(cls_id, cls_id):<22} conf={c:.3f}")
# only draw/keep boxes that clear the real threshold
keep = result.boxes.conf >= args.conf
result = result[keep]
draw_detections(frame, result)
return frame
# ---------------------------------------------------------------------------
# Camera / video source handling
# ---------------------------------------------------------------------------
def build_csi_pipeline(width=1280, height=720, fps=30):
"""GStreamer pipeline for a Jetson CSI camera via nvarguscamerasrc."""
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) # video file path
# ---------------------------------------------------------------------------
# Main loops
# ---------------------------------------------------------------------------
def run_live_or_video(args, model):
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))
prev_t = time.time()
print("Press 'q' to quit.")
while True:
ok, frame = cap.read()
if not ok:
print("End of stream / camera read failed.")
break
frame = run_on_frame(frame, model, args)
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)
if writer is not None:
writer.write(frame)
if not args.no_display:
cv2.imshow("Marker Detection", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cap.release()
if writer is not None:
writer.release()
cv2.destroyAllWindows()
def run_on_folder(args, model):
src_dir = Path(args.source)
out_dir = Path(args.save_dir or "./results")
out_dir.mkdir(parents=True, exist_ok=True)
image_paths = sorted(p for p in src_dir.glob("*") if p.suffix.lower() in IMAGE_EXTS)
if not image_paths:
raise RuntimeError(f"No images found in {src_dir}")
for img_path in image_paths:
frame = cv2.imread(str(img_path))
if frame is None:
print(f"Skipping unreadable file: {img_path}")
continue
frame = run_on_frame(frame, model, args)
out_path = out_dir / img_path.name
cv2.imwrite(str(out_path), frame)
print(f"Saved: {out_path}")
print(f"Done. {len(image_paths)} image(s) processed -> {out_dir}")
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
def parse_args():
p = argparse.ArgumentParser(description="Marker-only YOLO26 detection for Jetson Orin Nano")
p.add_argument("--source", type=str, default="0",
help="'0'/'1' for USB camera index, 'csi' for Jetson CSI camera, "
"a video file path, or a folder of images.")
p.add_argument("--weights", type=str, default=None,
help="Override path to marker weights (.pt or .engine). "
"Defaults to marker_best.pt in MODEL_DIR.")
p.add_argument("--save", type=str, default=None,
help="Output video path (only used for camera/video sources).")
p.add_argument("--save-dir", type=str, default=None,
help="Output folder for annotated images (only used when --source is a folder).")
p.add_argument("--imgsz", type=int, default=640,
help="Inference resolution. Raised to 640 by default for better accuracy "
"on small markers; try 416 if you need more FPS.")
p.add_argument("--conf", type=float, default=0.30,
help="Confidence threshold for displaying a detection. Lower this "
"(e.g. 0.15) if the model is missing markers it should catch.")
p.add_argument("--device", type=str, default="0",
help="'0' for the Jetson's GPU, 'cpu' to force CPU.")
p.add_argument("--quantize", type=int, default=16, choices=[8, 16, 32],
help="Inference precision: 16 = FP16 (default, recommended on Jetson "
"GPUs), 32 = FP32, 8 = INT8.")
p.add_argument("--no-display", action="store_true",
help="Don't open a live preview window (useful when running headless over SSH).")
p.add_argument("--debug", action="store_true",
help="Print every candidate box + confidence to the terminal each frame, "
"so you can tell a low-confidence miss from a real non-detection.")
p.add_argument("--export-tensorrt", action="store_true",
help="One-time: export marker_best.pt to a TensorRT .engine file, then exit.")
return p.parse_args()
def main():
args = parse_args()
if args.export_tensorrt:
export_tensorrt(imgsz=args.imgsz, quantize=args.quantize)
return
weights_path = Path(args.weights) if args.weights else MARKER_WEIGHTS
if not args.weights:
# If a TensorRT engine was already exported next to the .pt file,
# prefer it automatically — much faster load + warmup than .pt.
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))
print("Model loaded.")
# Confirm GPU vs CPU explicitly instead of relying on log-scraping.
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: --device requests GPU but CUDA is not available "
"to this torch build -> inference will silently run on CPU. "
"Check that you're using NVIDIA's Jetson-specific torch wheel.")
except Exception as e:
print(f"Could not check CUDA availability: {e}")
# Warm up: first inference call always pays a one-time CUDA kernel /
# TensorRT context init cost. Do it here so it doesn't hit your FPS
# counter or make the first on-screen frame feel like a freeze.
print("Warming up model (first-inference CUDA init)...")
warmup_start = time.time()
import numpy as np
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() - warmup_start:.2f}s.")
source_path = Path(args.source)
if source_path.is_dir():
run_on_folder(args, model)
else:
run_live_or_video(args, model)
if __name__ == "__main__":
main()