Spaces:
Sleeping
Sleeping
import cv2 | |
import numpy as np | |
from ultralytics import YOLO | |
import os | |
import random | |
import logging | |
from typing import List, Dict, Any | |
# Configure logging | |
logging.basicConfig( | |
filename="app.log", | |
level=logging.INFO, | |
format="%(asctime)s - %(levelname)s - %(message)s" | |
) | |
# Define base directory and model path | |
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) | |
MODEL_PATH = os.path.abspath(os.path.join(BASE_DIR, "../../models/yolov8m.pt")) | |
# Initialize YOLO model | |
try: | |
model = YOLO(MODEL_PATH) | |
logging.info("Loaded YOLOv8m model for crack detection.") | |
logging.info(f"Model class names: {model.names}") | |
except Exception as e: | |
logging.error(f"Failed to load YOLOv8m model: {str(e)}") | |
model = None | |
def detect_cracks_and_objects(frame: np.ndarray) -> List[Dict[str, Any]]: | |
# Validate input frame | |
if not isinstance(frame, np.ndarray) or frame.size == 0: | |
logging.error("Invalid input frame provided to crack_detection.") | |
return [] | |
# Check if model is loaded | |
if model is None: | |
logging.error("YOLO model not loaded. Skipping crack detection.") | |
return [] | |
try: | |
# Perform YOLO inference | |
results = model(frame, verbose=False) | |
logging.debug("Completed YOLO inference for crack detection.") | |
except Exception as e: | |
logging.error(f"Error during YOLO inference: {str(e)}") | |
return [] | |
detections: List[Dict[str, Any]] = [] | |
line_counter = 1 | |
for r in results: | |
for box in r.boxes: | |
conf = float(box.conf[0]) | |
if conf < 0.3: | |
continue | |
cls = int(box.cls[0]) | |
label = model.names[cls] | |
if label != "crack": | |
continue | |
xyxy = box.xyxy[0].cpu().numpy().astype(int) | |
x_min, y_min, x_max, y_max = xyxy | |
severity = random.choice(["low", "medium", "high"]) | |
detection_label = f"Line {line_counter} - {label.capitalize()} (Conf: {conf:.2f})" | |
detections.append({ | |
"type": label, | |
"label": detection_label, | |
"confidence": conf, | |
"coordinates": [x_min, y_min, x_max, y_max], | |
"severity": severity | |
}) | |
line_counter += 1 | |
logging.info(f"Detected {len(detections)} cracks in operations_maintenance.") | |
return detections |