diff --git a/paint_defect_inference.py b/paint_defect_inference.py index dd22ca6..cc75f3d 100644 --- a/paint_defect_inference.py +++ b/paint_defect_inference.py @@ -1,154 +1,322 @@ +import argparse import cv2 import torch -import argparse from pathlib import Path from ultralytics import YOLO -# ---------------- CONFIGURATION ---------------- -MODEL_PATH = "/home/YOUR_USERNAME/best.pt" + +# ============================================================ +# Configuration +# ============================================================ + +# Update this path to the actual location of your trained model. +MODEL_PATH = "/home/YOUR_USERNAME/projects/paint_defect_detection/best.pt" + IMAGE_SIZE = 832 CONFIDENCE = 0.25 -# ------------------------------------------------ +# All results are saved directly in this folder. +OUTPUT_DIR = Path.home() / "projects" / "paint_defect_detection" / "results" + + +# ============================================================ +# Helper functions +# ============================================================ + +def get_device(): + """Use CUDA when available; otherwise use CPU.""" + if torch.cuda.is_available(): + print("Using CUDA GPU") + return 0 + + print("CUDA is unavailable. Using CPU.") + return "cpu" + + +def prepare_output_directory(): + """Create the results directory if it does not exist.""" + OUTPUT_DIR.mkdir(parents=True, exist_ok=True) + print(f"Results directory: {OUTPUT_DIR}") + + +def get_unique_path(output_path): + """Avoid overwriting an existing result file.""" + if not output_path.exists(): + return output_path + + counter = 1 + + while True: + new_path = output_path.with_name( + f"{output_path.stem}_{counter}{output_path.suffix}" + ) + + if not new_path.exists(): + return new_path + + counter += 1 + + +# ============================================================ +# Image inference +# ============================================================ + +def process_image(model, source, device): + """Run inference on an image and save the annotated image.""" + source_path = Path(source).expanduser() + + if not source_path.is_file(): + raise FileNotFoundError(f"Image not found: {source_path}") + + results = model.predict( + source=str(source_path), + imgsz=IMAGE_SIZE, + conf=CONFIDENCE, + device=device, + save=False, + verbose=True + ) + + for result in results: + annotated_image = result.plot() + + output_path = get_unique_path( + OUTPUT_DIR / f"{source_path.stem}_detected.jpg" + ) + + if not cv2.imwrite(str(output_path), annotated_image): + raise RuntimeError(f"Could not save image: {output_path}") + + print(f"Saved image: {output_path}") + + +# ============================================================ +# Video inference +# ============================================================ + +def process_video(model, source, device, display=True): + """Run inference on a video and save the annotated video.""" + source_path = Path(source).expanduser() + + if not source_path.is_file(): + raise FileNotFoundError(f"Video not found: {source_path}") + + cap = cv2.VideoCapture(str(source_path)) + + if not cap.isOpened(): + raise RuntimeError(f"Could not open video: {source_path}") + + fps = cap.get(cv2.CAP_PROP_FPS) + if fps <= 0: + fps = 25.0 + + width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + + output_path = get_unique_path( + OUTPUT_DIR / f"{source_path.stem}_detected.mp4" + ) + + fourcc = cv2.VideoWriter_fourcc(*"mp4v") + writer = cv2.VideoWriter( + str(output_path), + fourcc, + fps, + (width, height) + ) + + if not writer.isOpened(): + cap.release() + raise RuntimeError(f"Could not create output video: {output_path}") + + print("Processing video. Press Q to stop early.") + + try: + while True: + ret, frame = cap.read() + + if not ret: + break + + results = model.predict( + source=frame, + imgsz=IMAGE_SIZE, + conf=CONFIDENCE, + device=device, + verbose=False + ) + + annotated_frame = results[0].plot() + writer.write(annotated_frame) + + if display: + cv2.imshow("Paint Defect Detection", annotated_frame) + + if cv2.waitKey(1) & 0xFF == ord("q"): + break + + finally: + cap.release() + writer.release() + + if display: + cv2.destroyAllWindows() + + print(f"Saved video: {output_path}") + + +# ============================================================ +# Live camera inference +# ============================================================ + +def process_camera(model, source, device, display=True): + """Run live camera inference and save the annotated recording.""" + camera_index = int(source) + cap = cv2.VideoCapture(camera_index) + + if not cap.isOpened(): + raise RuntimeError( + f"Could not open camera index {camera_index}. " + "Check the camera connection and permissions." + ) + + # Use the camera's reported dimensions when available. + width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) or 640 + height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) or 480 + fps = cap.get(cv2.CAP_PROP_FPS) + + if fps <= 0 or fps > 120: + fps = 20.0 + + output_path = get_unique_path( + OUTPUT_DIR / "paint_defects_camera.mp4" + ) + + fourcc = cv2.VideoWriter_fourcc(*"mp4v") + writer = cv2.VideoWriter( + str(output_path), + fourcc, + fps, + (width, height) + ) + + if not writer.isOpened(): + cap.release() + raise RuntimeError(f"Could not create output video: {output_path}") + + print("Live detection started. Press Q to stop.") + + try: + while True: + ret, frame = cap.read() + + if not ret: + print("Could not read a frame from the camera.") + break + + results = model.predict( + source=frame, + imgsz=IMAGE_SIZE, + conf=CONFIDENCE, + device=device, + verbose=False + ) + + annotated_frame = results[0].plot() + writer.write(annotated_frame) + + if display: + cv2.imshow("Paint Defect Detection", annotated_frame) + + if cv2.waitKey(1) & 0xFF == ord("q"): + break + + finally: + cap.release() + writer.release() + + if display: + cv2.destroyAllWindows() + + print(f"Saved camera recording: {output_path}") + + +# ============================================================ +# Main +# ============================================================ def main(): parser = argparse.ArgumentParser( - description="Paint defect detection using trained YOLO26s" + description="Paint defect detection using a trained YOLO model" ) + parser.add_argument( "--source", + type=str, default="0", - help="Camera index (0), image path, or video path" - ) - parser.add_argument( - "--output", - default="inference_results", - help="Directory for saved results" + help="Image path, video path, or camera index (default: 0)" ) + parser.add_argument( "--no-display", action="store_true", - help="Do not display the inference window" + help="Run without opening a display window" ) + args = parser.parse_args() - model_path = Path(MODEL_PATH) + prepare_output_directory() + + model_path = Path(MODEL_PATH).expanduser() + if not model_path.is_file(): raise FileNotFoundError( - f"Model not found: {model_path}. Update MODEL_PATH." + f"Model weights not found: {model_path}\n" + "Update MODEL_PATH at the top of this script." ) - print("Loading paint defect detection model...") - print("PyTorch version:", torch.__version__) - print("CUDA available:", torch.cuda.is_available()) - - if not torch.cuda.is_available(): - print("WARNING: CUDA is unavailable. Inference may run on CPU.") - device = "cpu" - else: - device = 0 - print("GPU:", torch.cuda.get_device_name(0)) + device = get_device() + print(f"Loading model: {model_path}") model = YOLO(str(model_path)) - print("Classes:", model.names) - # Camera input: live inference - if args.source.isdigit(): - camera_id = int(args.source) - cap = cv2.VideoCapture(camera_id) + source = args.source.strip() + display = not args.no_display - if not cap.isOpened(): - raise RuntimeError( - f"Could not open camera {camera_id}. " - "Check the camera connection and device index." - ) - - cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280) - cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720) - - output_dir = Path(args.output) - output_dir.mkdir(parents=True, exist_ok=True) - output_path = output_dir / "paint_defects_camera.mp4" - - fps = cap.get(cv2.CAP_PROP_FPS) - if not fps or fps <= 1: - fps = 20.0 - - width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) - height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) - - writer = None - if not args.no_display: - fourcc = cv2.VideoWriter_fourcc(*"mp4v") - writer = cv2.VideoWriter( - str(output_path), fourcc, fps, (width, height) - ) - - print("Camera inference started. Press Q to stop.") - - try: - while True: - ret, frame = cap.read() - if not ret: - print("Could not read camera frame.") - break - - results = model.predict( - source=frame, - imgsz=IMAGE_SIZE, - conf=CONFIDENCE, - device=device, - verbose=False - ) - - annotated = results[0].plot() - - if writer is not None: - writer.write(annotated) - - if not args.no_display: - cv2.imshow("Paint Defect Detection", annotated) - if cv2.waitKey(1) & 0xFF == ord("q"): - break - - finally: - cap.release() - if writer is not None: - writer.release() - cv2.destroyAllWindows() - - print("Camera inference stopped.") - if not args.no_display: - print("Annotated video:", output_path) + # A numeric source means a live camera index. + if source.isdigit(): + process_camera(model, source, device, display) else: - # Image or video inference; save annotated output. - results = model.predict( - source=args.source, - imgsz=IMAGE_SIZE, - conf=CONFIDENCE, - device=device, - save=True, - project=args.output, - name="predict", - exist_ok=True, - show=not args.no_display, - verbose=True - ) + source_path = Path(source).expanduser() - for result in results: - print("Processed:", result.path) - if result.boxes is not None: - for box in result.boxes: - class_id = int(box.cls.item()) - confidence = float(box.conf.item()) - print( - f" {model.names[class_id]}: " - f"{confidence:.2%}" - ) + if not source_path.exists(): + raise FileNotFoundError(f"Source not found: {source_path}") - print("Results saved under:", args.output) + image_extensions = { + ".jpg", ".jpeg", ".png", ".bmp", ".webp", ".tif", ".tiff" + } + + video_extensions = { + ".mp4", ".avi", ".mov", ".mkv", ".mpeg", ".mpg", ".m4v" + } + + extension = source_path.suffix.lower() + + if extension in image_extensions: + process_image(model, source_path, device) + + elif extension in video_extensions: + process_video(model, source_path, device, display) + + else: + raise ValueError( + f"Unsupported source type: {extension}\n" + "Provide an image, video, or camera index." + ) + + print("Inference completed.") if __name__ == "__main__":