lokesh341 commited on
Commit
609231f
·
verified ·
1 Parent(s): b9160f0

Update services/road_safety/pothole_crack_detection.py

Browse files
services/road_safety/pothole_crack_detection.py CHANGED
@@ -1,100 +1,40 @@
1
  import cv2
2
  import numpy as np
3
  from ultralytics import YOLO
4
- import os
5
- import random
6
- import logging
7
- from typing import Tuple, List, Dict, Any
8
 
9
- # Configure logging
10
- logging.basicConfig(
11
- filename="app.log",
12
- level=logging.INFO,
13
- format="%(asctime)s - %(levelname)s - %(message)s"
14
- )
15
-
16
- # Define base directory and model path
17
- BASE_DIR = os.path.dirname(os.path.abspath(__file__))
18
- MODEL_PATH = os.path.abspath(os.path.join(BASE_DIR, "../../models/yolov8m-seg.pt"))
19
-
20
- # Initialize YOLO model
21
- try:
22
- model = YOLO(MODEL_PATH)
23
- logging.info("Successfully loaded YOLOv8m-seg model for pothole and crack detection.")
24
- logging.info(f"Model class names: {model.names}")
25
- except Exception as e:
26
- logging.error(f"Failed to load YOLOv8m-seg model: {str(e)}")
27
- model = None
28
 
29
  def detect_potholes_and_cracks(frame: np.ndarray) -> Tuple[List[Dict[str, Any]], np.ndarray]:
30
- # Validate input frame
31
- if not isinstance(frame, np.ndarray) or frame.size == 0:
32
- logging.error("Invalid input frame provided to pothole_crack_detection.")
33
- return [], frame
34
-
35
- # Check if model is loaded
36
- if model is None:
37
- logging.error("YOLO model not loaded. Skipping pothole and crack detection.")
38
- return [], frame
39
-
40
- try:
41
- # Perform YOLO inference
42
- results = model(frame, verbose=False)
43
- logging.debug("Completed YOLO inference for pothole and crack detection.")
44
- except Exception as e:
45
- logging.error(f"Error during YOLO inference: {str(e)}")
46
- return [], frame
47
-
48
- detections: List[Dict[str, Any]] = []
49
- line_counter = 1
50
-
51
- for result in results:
52
- for box in result.boxes:
53
- conf = float(box.conf[0])
54
- if conf < 0.3:
55
- continue
56
-
57
- cls = int(box.cls[0])
58
- label = model.names[cls]
59
- if label not in ["crack", "pothole", "debris"]:
60
- continue
61
-
62
- xyxy = box.xyxy[0].cpu().numpy().astype(int)
63
- x_min, y_min, x_max, y_max = xyxy
64
-
65
- severity = None
66
- if label == "crack":
67
- color = (255, 0, 0) # Red for cracks
68
- severity = random.choice(["low", "medium", "high"])
69
- elif label == "pothole":
70
- color = (255, 0, 0) # Red for potholes
71
- else: # debris
72
- color = (255, 215, 0) # Gold for debris
73
-
74
- detection_label = f"Line {line_counter} - {label.capitalize()} (Conf: {conf:.2f})"
75
- item = {
76
- "type": label,
77
- "label": detection_label,
78
- "confidence": conf,
79
- "coordinates": [x_min, y_min, x_max, y_max]
80
- }
81
- if severity:
82
- item["severity"] = severity
83
-
84
- detections.append(item)
85
-
86
- cv2.rectangle(frame, (x_min, y_min), (x_max, y_max), color, 2)
87
- cv2.putText(
88
- frame,
89
- detection_label,
90
- (x_min, y_min - 10),
91
- cv2.FONT_HERSHEY_SIMPLEX,
92
- 0.6,
93
- color,
94
- 2
95
- )
96
-
97
- line_counter += 1
98
-
99
- logging.info(f"Detected {len(detections)} potholes/cracks/debris in road_safety.")
100
  return detections, frame
 
1
  import cv2
2
  import numpy as np
3
  from ultralytics import YOLO
4
+ from typing import List, Tuple, Dict, Any
 
 
 
5
 
6
+ # Load YOLOv8 model for pothole and crack detection
7
+ model = YOLO("models/yolov8n.pt") # Use lighter model for faster inference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  def detect_potholes_and_cracks(frame: np.ndarray) -> Tuple[List[Dict[str, Any]], np.ndarray]:
10
+ """
11
+ Detect potholes and cracks in the frame using YOLOv8.
12
+ Args:
13
+ frame: Input frame as a numpy array.
14
+ Returns:
15
+ Tuple of (list of detections, annotated frame).
16
+ """
17
+ # Perform inference
18
+ results = model(frame, classes=[0, 1], conf=0.5) # Assuming class 0 is pothole, class 1 is crack
19
+
20
+ detections = []
21
+ for i, r in enumerate(results[0].boxes):
22
+ x_min, y_min, x_max, y_max = map(int, r.xyxy[0])
23
+ conf = float(r.conf)
24
+ cls = int(r.cls)
25
+ dtype = "hole" if cls == 0 else "crack"
26
+ label = f"{dtype.capitalize()} {i+1}"
27
+
28
+ # Determine severity based on confidence and size
29
+ area = (x_max - x_min) * (y_max - y_min)
30
+ severity = "Severe" if area > 1000 or conf > 0.8 else "Moderate" if area > 500 or conf > 0.6 else "Mild"
31
+
32
+ detections.append({
33
+ "box": [x_min, y_min, x_max, y_max],
34
+ "label": label,
35
+ "type": dtype,
36
+ "confidence": conf,
37
+ "severity": severity
38
+ })
39
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  return detections, frame