Files
welding/2_infer_image.py
T

100 lines
3.2 KiB
Python

#!/usr/bin/env python3
"""
Step 2: weld detection on image(s) using best_weld.engine
USAGE
-----
Auto-pick the first image in the welding folder:
python3 2_infer_image.py
Specific image:
python3 2_infer_image.py --source weld.jpg
Folder of images:
python3 2_infer_image.py --source ./test_images
Extras:
--show open a preview window
--debug print every candidate box, even below --conf
--conf 0.15 lower the threshold if welds/defects are being missed
"""
import argparse
import sys
from pathlib import Path
import cv2
from weld_common import (CONF, DEVICE, IMAGE_EXTS, IMGSZ, IOU, RESULTS_DIR,
counts_to_str, detect, draw_detections, find_first, load_model)
def parse_args():
p = argparse.ArgumentParser(description="Weld detection on images (TensorRT engine)")
p.add_argument("--source", type=str, default=None,
help="Image file or folder. Default: first image 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))
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("--show", action="store_true", help="Show a preview window.")
p.add_argument("--debug", action="store_true")
return p.parse_args()
def collect_images(source):
if source is None:
first = find_first(IMAGE_EXTS)
if first is None:
sys.exit("No image found in the welding folder. Use --source path/to/image.jpg")
print(f"No --source given, using: {first.name}")
return [first]
path = Path(source)
if path.is_dir():
imgs = sorted(p for p in path.iterdir() if p.suffix.lower() in IMAGE_EXTS)
if not imgs:
sys.exit(f"No images found in {path}")
return imgs
if not path.exists():
sys.exit(f"File not found: {path}")
return [path]
def main():
args = parse_args()
images = collect_images(args.source)
model = load_model(args.weights, args.imgsz, args.device)
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}")
if __name__ == "__main__":
main()