#!/usr/bin/env python3 """ Step 3: weld detection on video / camera using best_weld.engine USAGE ----- Auto-pick the first video in the welding folder (output saved to results/): python3 3_infer_video.py Specific video: python3 3_infer_video.py --source weld.mp4 USB camera / Jetson CSI camera: python3 3_infer_video.py --source 0 python3 3_infer_video.py --source csi Headless over SSH (no window): python3 3_infer_video.py --no-display Extras: --no-save don't write an output video --debug print every candidate box each frame --conf 0.15 lower the threshold if welds/defects are being missed Press 'q' in the preview window to quit. """ import argparse import sys import time from pathlib import Path import cv2 from weld_common import (CONF, DEVICE, IMGSZ, IOU, RESULTS_DIR, VIDEO_EXTS, counts_to_str, detect, draw_detections, find_first, load_model) 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) def parse_args(): p = argparse.ArgumentParser(description="Weld detection on video (TensorRT engine)") p.add_argument("--source", type=str, default=None, help="Video file, '0'/'1' for USB camera, or 'csi'. " "Default: first video in the welding folder.") p.add_argument("--weights", type=str, default=None, help="Override engine path.") p.add_argument("--save", type=str, default=None, help="Output video path. Default: results/_out.mp4") p.add_argument("--no-save", action="store_true", help="Don't write an output video.") p.add_argument("--imgsz", type=int, default=IMGSZ, help="Must match the engine's imgsz.") p.add_argument("--conf", type=float, default=CONF) p.add_argument("--iou", type=float, default=IOU) p.add_argument("--device", type=str, default=DEVICE) p.add_argument("--no-display", action="store_true") p.add_argument("--debug", action="store_true") return p.parse_args() def main(): args = parse_args() source = args.source if source is None: first = find_first(VIDEO_EXTS) if first is None: sys.exit("No video found in the welding folder. Use --source path/to/video.mp4") print(f"No --source given, using: {first.name}") source = str(first) model = load_model(args.weights, args.imgsz, args.device) cap = open_capture(source) if not cap.isOpened(): sys.exit(f"Could not open source: {source}") writer = None if not args.no_save: if args.save: out_path = Path(args.save) else: name = "camera" if (source == "csi" or source.isdigit()) else Path(source).stem out_path = RESULTS_DIR / f"{name}_out.mp4" out_path.parent.mkdir(parents=True, exist_ok=True) 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(str(out_path), cv2.VideoWriter_fourcc(*"mp4v"), fps_out, (w, h)) print(f"Saving output to: {out_path}") total_counts = {} frames = 0 prev_t = time.time() print("Running... press 'q' to quit.") while True: ok, frame = cap.read() if not ok: print("End of stream / camera read failed.") break result = detect(model, frame, args.conf, args.iou, args.imgsz, args.device, args.debug) counts = draw_detections(frame, result, model.names) for k, v in counts.items(): total_counts[k] = total_counts.get(k, 0) + v 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.putText(frame, counts_to_str(counts), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2) if writer is not None: writer.write(frame) if not args.no_display: cv2.imshow("Weld Detection", frame) if cv2.waitKey(1) & 0xFF == ord("q"): break frames += 1 cap.release() if writer is not None: writer.release() cv2.destroyAllWindows() print(f"\nProcessed {frames} frame(s). Total detections: {counts_to_str(total_counts)}") if __name__ == "__main__": main()