353 lines
13 KiB
Python
353 lines
13 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
infer.py - weld detection with best_weld.engine on images, video, or a live camera.
|
|
|
|
The script looks at --source and picks the mode by itself:
|
|
image file / folder of images -> image mode
|
|
video file / 0 / 1 / csi -> video mode (live camera or file)
|
|
|
|
Project root : /home/jetson/projects_2026/welding
|
|
models/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
|
|
|
|
USAGE
|
|
-----
|
|
No --source: first image found, else first video found:
|
|
python3 infer.py
|
|
|
|
Images:
|
|
python3 infer.py --source weld.jpg
|
|
python3 infer.py --source ./test_images
|
|
python3 infer.py --source ./test_images --show # preview window
|
|
|
|
Video file:
|
|
python3 infer.py --source test_video.mp4
|
|
|
|
Live camera:
|
|
python3 infer.py --source 0 # USB camera
|
|
python3 infer.py --source csi # Jetson CSI camera
|
|
|
|
Headless over SSH (no window):
|
|
python3 infer.py --source 0 --no-display
|
|
|
|
Extras (work in every mode):
|
|
--conf 0.15 lower the threshold if welds/defects are being missed
|
|
--debug print every candidate box, even below --conf
|
|
--no-save (video) don't write an output video
|
|
|
|
Press 'q' in a preview window to quit.
|
|
"""
|
|
|
|
import argparse
|
|
import os
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import cv2
|
|
import numpy as np
|
|
from ultralytics import YOLO
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# CONFIG
|
|
# ---------------------------------------------------------------------------
|
|
# Override without editing the file: export WELD_HOME=/other/path
|
|
BASE_DIR = Path(os.environ.get("WELD_HOME", "/home/jetson/projects_2026/welding"))
|
|
|
|
MODELS_DIR = BASE_DIR / "models"
|
|
TEST_IMAGES_DIR = BASE_DIR / "test_images"
|
|
RESULTS_DIR = BASE_DIR / "results" # all outputs are saved here
|
|
ENGINE_PATH = MODELS_DIR / "best_weld.engine"
|
|
|
|
# The engine is locked to the imgsz it was built with. Training used 640.
|
|
IMGSZ = 640
|
|
CONF = 0.25
|
|
IOU = 0.45
|
|
DEVICE = "0" # Jetson GPU
|
|
|
|
IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp"}
|
|
VIDEO_EXTS = {".mp4", ".avi", ".mov", ".mkv"}
|
|
|
|
# Where the default source is searched when --source is not given (in 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)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Model helpers
|
|
# ---------------------------------------------------------------------------
|
|
def load_model(weights, imgsz, device):
|
|
"""Load the engine, print class names, and warm it up."""
|
|
path = Path(weights) if weights else ENGINE_PATH
|
|
if not path.exists():
|
|
hint = ("Run 'python3 convert.py' first to build the engine."
|
|
if path == ENGINE_PATH else "Check the --weights path.")
|
|
sys.exit(f"Weights not found: {path}\n{hint}")
|
|
|
|
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, iou, imgsz, 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"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Source handling
|
|
# ---------------------------------------------------------------------------
|
|
def find_first(exts):
|
|
"""First file with a suffix in exts, searched in DEFAULT_SEARCH_DIRS order."""
|
|
for d in DEFAULT_SEARCH_DIRS:
|
|
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 classify_source(source):
|
|
"""Return (mode, source) where mode is 'image' or 'video'."""
|
|
if source is None:
|
|
img = find_first(IMAGE_EXTS)
|
|
if img is not None:
|
|
print(f"No --source given, using image: {img.name}")
|
|
return "image", str(img)
|
|
vid = find_first(VIDEO_EXTS)
|
|
if vid is not None:
|
|
print(f"No --source given, using video: {vid.name}")
|
|
return "video", str(vid)
|
|
sys.exit("No image or video found. Use --source path/to/file (or 0 / csi for a camera).")
|
|
|
|
if source == "csi" or source.isdigit():
|
|
return "video", source
|
|
|
|
path = Path(source)
|
|
if not path.exists():
|
|
sys.exit(f"Source not found: {source}")
|
|
if path.is_dir():
|
|
return "image", source
|
|
if path.suffix.lower() in IMAGE_EXTS:
|
|
return "image", source
|
|
if path.suffix.lower() in VIDEO_EXTS:
|
|
return "video", source
|
|
sys.exit(f"Unsupported file type: {path.suffix}")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Image mode
|
|
# ---------------------------------------------------------------------------
|
|
def run_images(model, source, args):
|
|
path = Path(source)
|
|
if path.is_dir():
|
|
images = sorted(p for p in path.iterdir() if p.suffix.lower() in IMAGE_EXTS)
|
|
if not images:
|
|
sys.exit(f"No images found in {path}")
|
|
else:
|
|
images = [path]
|
|
|
|
out_dir = Path(args.save_dir)
|
|
out_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
for img_path in images:
|
|
frame = cv2.imread(str(img_path))
|
|
if frame is None:
|
|
print(f"Skipping unreadable file: {img_path}")
|
|
continue
|
|
|
|
print(f"\n{img_path.name}")
|
|
result = detect(model, frame, args.conf, args.iou, args.imgsz, args.device, args.debug)
|
|
counts = draw_detections(frame, result, model.names)
|
|
print(f" -> {counts_to_str(counts)}")
|
|
|
|
out_path = out_dir / f"{img_path.stem}_out{img_path.suffix}"
|
|
cv2.imwrite(str(out_path), frame)
|
|
print(f" Saved: {out_path}")
|
|
|
|
if args.show:
|
|
cv2.imshow("Weld Detection", frame)
|
|
if cv2.waitKey(0) & 0xFF == ord("q"):
|
|
break
|
|
|
|
cv2.destroyAllWindows()
|
|
print(f"\nDone. {len(images)} image(s) -> {out_dir}")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Video / camera mode
|
|
# ---------------------------------------------------------------------------
|
|
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):
|
|
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 run_video(model, source, args):
|
|
cap = open_capture(source)
|
|
if not cap.isOpened():
|
|
sys.exit(f"Could not open source: {source}")
|
|
|
|
is_camera = source == "csi" or source.isdigit()
|
|
|
|
writer = None
|
|
if not args.no_save:
|
|
if args.save:
|
|
out_path = Path(args.save)
|
|
else:
|
|
name = "camera" if is_camera else Path(source).stem
|
|
out_path = Path(args.save_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.")
|
|
|
|
try:
|
|
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
|
|
except KeyboardInterrupt:
|
|
print("\nStopped by user (Ctrl+C).")
|
|
finally:
|
|
cap.release()
|
|
if writer is not None:
|
|
writer.release()
|
|
cv2.destroyAllWindows()
|
|
|
|
print(f"\nProcessed {frames} frame(s). Total detections: {counts_to_str(total_counts)}")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
def parse_args():
|
|
p = argparse.ArgumentParser(
|
|
description="Weld detection (TensorRT engine) on images, video, or live camera")
|
|
p.add_argument("--source", type=str, default=None,
|
|
help="Image file/folder, video file, '0'/'1' for USB camera, or 'csi'. "
|
|
"Default: first image (else first video) in the welding folder.")
|
|
p.add_argument("--weights", type=str, default=None, help="Override engine path.")
|
|
p.add_argument("--save-dir", type=str, default=str(RESULTS_DIR),
|
|
help="Output folder. Default: results/")
|
|
p.add_argument("--save", type=str, default=None,
|
|
help="(video) exact output video path. Default: results/<name>_out.mp4")
|
|
p.add_argument("--no-save", action="store_true", help="(video) don't write an output video.")
|
|
p.add_argument("--show", action="store_true", help="(images) show a preview window.")
|
|
p.add_argument("--no-display", action="store_true", help="(video) no preview window.")
|
|
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("--debug", action="store_true",
|
|
help="Print every candidate box, even below --conf.")
|
|
return p.parse_args()
|
|
|
|
|
|
def main():
|
|
args = parse_args()
|
|
mode, source = classify_source(args.source)
|
|
model = load_model(args.weights, args.imgsz, args.device)
|
|
|
|
if mode == "image":
|
|
run_images(model, source, args)
|
|
else:
|
|
run_video(model, source, args)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|