#!/usr/bin/env python3 """ Shared config + helpers for the weld detection scripts. Project root : /home/jetson/projects/welding models/ best_weld.pt, best_weld.onnx, best_weld.engine test_images/ input images test_video.mp4 input video (any .mp4/.avi/.mov/.mkv in the root also works) results/ ALL outputs (annotated images + videos) are saved here Classes (read from the model itself; training order): Bad Weld, Good Weld, Defect Edit the CONFIG block below if your names or training size differ. """ import os from pathlib import Path import cv2 from ultralytics import YOLO # --------------------------------------------------------------------------- # CONFIG # --------------------------------------------------------------------------- # Project root. Override without editing the file: export WELD_HOME=/other/path BASE_DIR = Path(os.environ.get("WELD_HOME", "/home/jetson/projects/welding")) MODELS_DIR = BASE_DIR / "models" TEST_IMAGES_DIR = BASE_DIR / "test_images" RESULTS_DIR = BASE_DIR / "results" # <- all outputs are saved here PT_PATH = MODELS_DIR / "best_weld.pt" ONNX_PATH = MODELS_DIR / "best_weld.onnx" ENGINE_PATH = MODELS_DIR / "best_weld.engine" # IMPORTANT: a TensorRT engine is locked to the imgsz it was built with. # Training used imgsz=640, so keep 640 unless you rebuild the engine. IMGSZ = 640 CONF = 0.25 IOU = 0.45 DEVICE = "0" # Jetson GPU. Use "cpu" only for .pt/.onnx testing. IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp"} VIDEO_EXTS = {".mp4", ".avi", ".mov", ".mkv"} # Where find_first() looks when --source is not given (in this order). DEFAULT_SEARCH_DIRS = [TEST_IMAGES_DIR, BASE_DIR, BASE_DIR / "test_videos"] # BGR colours per class name (case-insensitive). Unknown names get a fallback. CLASS_COLORS = { "bad weld": (0, 0, 255), # red "defect": (0, 165, 255), # orange "good weld": (0, 200, 0), # green } FALLBACK_COLOR = (255, 255, 0) # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- def find_first(exts, folder=None): """Return the first file whose suffix is in exts. Searches folder if given, otherwise DEFAULT_SEARCH_DIRS in order (test_images/, then the project root, then test_videos/). Returns None if nothing matches. """ folders = [Path(folder)] if folder else DEFAULT_SEARCH_DIRS for d in folders: if not d.is_dir(): continue for p in sorted(d.iterdir()): if p.is_file() and p.suffix.lower() in exts: return p return None def resolve_weights(weights=None): """Use --weights if given, else models/best_weld.engine. Never silently falls back to .pt.""" path = Path(weights) if weights else ENGINE_PATH if not path.exists(): hint = ("Run 1_convert.py first to build the engine." if path == ENGINE_PATH else "Check the --weights path.") raise FileNotFoundError(f"Weights not found: {path}\n{hint}") return path def load_model(weights=None, imgsz=IMGSZ, device=DEVICE): """Load the model, print class names, and warm it up.""" import numpy as np path = resolve_weights(weights) print(f"Loading model: {path}") model = YOLO(str(path), task="detect") print(f"Classes: {model.names}") print("Warming up (first-inference CUDA/TensorRT init)...") dummy = np.zeros((imgsz, imgsz, 3), dtype="uint8") model.predict(source=dummy, imgsz=imgsz, device=device, verbose=False) print("Ready.") return model def detect(model, frame, conf=CONF, iou=IOU, imgsz=IMGSZ, device=DEVICE, debug=False): """Run inference on one BGR frame and return the Ultralytics result.""" run_conf = 0.05 if debug else conf result = model.predict(source=frame, conf=run_conf, iou=iou, imgsz=imgsz, device=device, verbose=False)[0] if debug: if len(result.boxes) == 0: print(" (no candidate boxes)") for box in result.boxes: c = float(box.conf[0]) name = model.names[int(box.cls[0])] flag = "OK " if c >= conf else "low" print(f" [{flag}] {name:<12} conf={c:.3f}") result = result[result.boxes.conf >= conf] return result def draw_detections(frame, result, names): """Draw boxes + labels on the frame in place. Returns {class_name: count}.""" counts = {} 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]) name = names.get(cls_id, str(cls_id)) counts[name] = counts.get(name, 0) + 1 color = CLASS_COLORS.get(name.lower(), FALLBACK_COLOR) label = f"{name} {conf:.2f}" cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2) (tw, th), base = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.55, 2) top = max(y1 - th - base - 4, 0) cv2.rectangle(frame, (x1, top), (x1 + tw + 4, top + th + base + 4), color, -1) cv2.putText(frame, label, (x1 + 2, top + th + 1), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (255, 255, 255), 2) return counts def counts_to_str(counts): return ", ".join(f"{k}: {v}" for k, v in sorted(counts.items())) or "no detections"