324 lines
8.3 KiB
Python
324 lines
8.3 KiB
Python
|
|
import argparse
|
|
import cv2
|
|
import torch
|
|
from pathlib import Path
|
|
from ultralytics import YOLO
|
|
|
|
|
|
# ============================================================
|
|
# 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 a trained YOLO model"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--source",
|
|
type=str,
|
|
default="0",
|
|
help="Image path, video path, or camera index (default: 0)"
|
|
)
|
|
|
|
parser.add_argument(
|
|
"--no-display",
|
|
action="store_true",
|
|
help="Run without opening a display window"
|
|
)
|
|
|
|
args = parser.parse_args()
|
|
|
|
prepare_output_directory()
|
|
|
|
model_path = Path(MODEL_PATH).expanduser()
|
|
|
|
if not model_path.is_file():
|
|
raise FileNotFoundError(
|
|
f"Model weights not found: {model_path}\n"
|
|
"Update MODEL_PATH at the top of this script."
|
|
)
|
|
|
|
device = get_device()
|
|
|
|
print(f"Loading model: {model_path}")
|
|
model = YOLO(str(model_path))
|
|
|
|
source = args.source.strip()
|
|
display = not args.no_display
|
|
|
|
# A numeric source means a live camera index.
|
|
if source.isdigit():
|
|
process_camera(model, source, device, display)
|
|
|
|
else:
|
|
source_path = Path(source).expanduser()
|
|
|
|
if not source_path.exists():
|
|
raise FileNotFoundError(f"Source not found: {source_path}")
|
|
|
|
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__":
|
|
main()
|