lokesh341 commited on
Commit
fd7e73c
·
verified ·
1 Parent(s): 83e8ad5

Update services/operations_maintenance/pothole_detection.py

Browse files
services/operations_maintenance/pothole_detection.py CHANGED
@@ -1,85 +1,37 @@
1
  import cv2
2
  import numpy as np
3
  from ultralytics import YOLO
4
- import os
5
- import logging
6
- from typing import Tuple, List, Dict, Any
7
 
8
- # Configure logging
9
- logging.basicConfig(
10
- filename="app.log",
11
- level=logging.INFO,
12
- format="%(asctime)s - %(levelname)s - %(message)s"
13
- )
14
-
15
- # Define base directory and model path
16
- BASE_DIR = os.path.dirname(os.path.abspath(__file__))
17
- MODEL_PATH = os.path.abspath(os.path.join(BASE_DIR, "../../models/yolov8m.pt"))
18
-
19
- # Initialize YOLO model
20
- try:
21
- model = YOLO(MODEL_PATH)
22
- logging.info("Loaded YOLOv8m model for pothole detection.")
23
- logging.info(f"Model class names: {model.names}")
24
- except Exception as e:
25
- logging.error(f"Failed to load YOLOv8m model: {str(e)}")
26
- model = None
27
 
28
  def process_potholes(frame: np.ndarray) -> Tuple[List[Dict[str, Any]], np.ndarray]:
29
- # Validate input frame
30
- if not isinstance(frame, np.ndarray) or frame.size == 0:
31
- logging.error("Invalid input frame provided to pothole_detection.")
32
- return [], frame
33
-
34
- # Check if model is loaded
35
- if model is None:
36
- logging.error("YOLO model not loaded. Skipping pothole detection.")
37
- return [], frame
38
-
39
- try:
40
- # Perform YOLO inference
41
- results = model(frame, verbose=False)
42
- logging.debug("Completed YOLO inference for pothole detection.")
43
- except Exception as e:
44
- logging.error(f"Error during YOLO inference: {str(e)}")
45
- return [], frame
46
-
47
- detections: List[Dict[str, Any]] = []
48
- line_counter = 1
49
-
50
- for r in results:
51
- for box in r.boxes:
52
- conf = float(box.conf[0])
53
- if conf < 0.3:
54
- continue
55
- cls = int(box.cls[0])
56
- label = model.names[cls]
57
- if label != "pothole":
58
- continue
59
- xyxy = box.xyxy[0].cpu().numpy().astype(int)
60
- x_min, y_min, x_max, y_max = xyxy
61
-
62
- detection_label = f"Line {line_counter} - {label.capitalize()} (Conf: {conf:.2f})"
63
- detections.append({
64
- "type": label,
65
- "label": detection_label,
66
- "confidence": conf,
67
- "coordinates": [x_min, y_min, x_max, y_max]
68
- })
69
-
70
- color = (255, 0, 0) # Red for potholes
71
- cv2.rectangle(frame, (x_min, y_min), (x_max, y_max), color, 2)
72
- cv2.putText(
73
- frame,
74
- detection_label,
75
- (x_min, y_min - 10),
76
- cv2.FONT_HERSHEY_SIMPLEX,
77
- 0.6,
78
- color,
79
- 2
80
- )
81
-
82
- line_counter += 1
83
-
84
- logging.info(f"Detected {len(detections)} potholes in operations_maintenance.")
85
  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 detection
7
+ model = YOLO("models/yolov8n.pt")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  def process_potholes(frame: np.ndarray) -> Tuple[List[Dict[str, Any]], np.ndarray]:
10
+ """
11
+ Detect potholes 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], conf=0.5) # Class 0 assumed for potholes
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
+
25
+ # Determine severity based on size
26
+ area = (x_max - x_min) * (y_max - y_min)
27
+ severity = "Severe" if area > 1000 or conf > 0.8 else "Moderate" if area > 500 or conf > 0.6 else "Mild"
28
+
29
+ detections.append({
30
+ "box": [x_min, y_min, x_max, y_max],
31
+ "label": f"Pothole {i+1}",
32
+ "type": "pothole",
33
+ "confidence": conf,
34
+ "severity": severity
35
+ })
36
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  return detections, frame