lokesh341 commited on
Commit
caa057f
·
1 Parent(s): fb723a9

Update services/road_safety/pothole_crack_detection.py

Browse files
services/road_safety/pothole_crack_detection.py CHANGED
@@ -6,39 +6,27 @@ import random
6
  import logging
7
  from typing import Tuple, List, Dict, Any
8
 
9
- # Configure logging to track script execution and errors
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 for YOLOv8m-seg
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 with error handling
21
  try:
22
  model = YOLO(MODEL_PATH)
23
  logging.info("Successfully loaded YOLOv8m-seg model for pothole and crack detection.")
24
- # Log the model's class names for debugging
25
  logging.info(f"Model class names: {model.names}")
26
  except Exception as e:
27
  logging.error(f"Failed to load YOLOv8m-seg model: {str(e)}")
28
  model = None
29
 
30
  def detect_potholes_and_cracks(frame: np.ndarray) -> Tuple[List[Dict[str, Any]], np.ndarray]:
31
- """
32
- Detect potholes, cracks, and debris in a video frame using YOLOv8m-seg.
33
-
34
- Args:
35
- frame (np.ndarray): Input frame in BGR format.
36
-
37
- Returns:
38
- Tuple[List[Dict[str, Any]], np.ndarray]: A tuple containing:
39
- - List of detected items (dictionaries with type, label, confidence, coordinates, and severity).
40
- - Annotated frame with bounding boxes and labels.
41
- """
42
  # Validate input frame
43
  if not isinstance(frame, np.ndarray) or frame.size == 0:
44
  logging.error("Invalid input frame provided to pothole_crack_detection.")
@@ -50,50 +38,40 @@ def detect_potholes_and_cracks(frame: np.ndarray) -> Tuple[List[Dict[str, Any]],
50
  return [], frame
51
 
52
  try:
53
- # Perform YOLO inference on the frame
54
- results = model(frame, verbose=False) # Suppress verbose output for cleaner logs
55
  logging.debug("Completed YOLO inference for pothole and crack detection.")
56
  except Exception as e:
57
  logging.error(f"Error during YOLO inference: {str(e)}")
58
  return [], frame
59
 
60
  detections: List[Dict[str, Any]] = []
61
- line_counter = 1 # Counter for numbered labels (e.g., "Line 1 - Crack")
62
 
63
- # Process each detection result
64
  for result in results:
65
  for box in result.boxes:
66
- # Extract confidence score and ensure it's above threshold
67
  conf = float(box.conf[0])
68
- if conf < 0.3: # Threshold set to 0.3 for better sensitivity
69
  continue
70
 
71
- # Extract class label
72
  cls = int(box.cls[0])
73
  label = model.names[cls]
74
-
75
- # Filter for relevant classes
76
  if label not in ["crack", "pothole", "debris"]:
77
  continue
78
 
79
- # Extract bounding box coordinates
80
  xyxy = box.xyxy[0].cpu().numpy().astype(int)
81
  x_min, y_min, x_max, y_max = xyxy
82
 
83
- # Assign color based on detection type (as per user requirements)
84
  severity = None
85
  if label == "crack":
86
  color = (255, 0, 0) # Red for cracks
87
  severity = random.choice(["low", "medium", "high"])
88
  elif label == "pothole":
89
- color = (0, 255, 0) # Green for potholes
90
  else: # debris
91
- color = (0, 0, 255) # Blue for debris
92
 
93
- # Create detection label with line number
94
  detection_label = f"Line {line_counter} - {label.capitalize()} (Conf: {conf:.2f})"
95
-
96
- # Create detection dictionary
97
  item = {
98
  "type": label,
99
  "label": detection_label,
@@ -105,7 +83,6 @@ def detect_potholes_and_cracks(frame: np.ndarray) -> Tuple[List[Dict[str, Any]],
105
 
106
  detections.append(item)
107
 
108
- # Draw bounding box and label on the frame
109
  cv2.rectangle(frame, (x_min, y_min), (x_max, y_max), color, 2)
110
  cv2.putText(
111
  frame,
 
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.")
 
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,
 
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,