lokesh341 commited on
Commit
edb10ef
·
1 Parent(s): 4fe77cf

Create pothole_crack_detection.py

Browse files
services/road_safety/pothole_crack_detection.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from ultralytics import YOLO
4
+ import os
5
+ import random
6
+ import logging
7
+
8
+ logging.basicConfig(
9
+ filename="app.log",
10
+ level=logging.INFO,
11
+ format="%(asctime)s - %(levelname)s - %(message)s"
12
+ )
13
+
14
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
15
+ MODEL_PATH = os.path.abspath(os.path.join(BASE_DIR, "../../models/yolov8m-seg.pt"))
16
+ try:
17
+ model = YOLO(MODEL_PATH)
18
+ logging.info("Loaded YOLOv8m-seg model for pothole and crack detection.")
19
+ except Exception as e:
20
+ logging.error(f"Failed to load YOLOv8m-seg model: {str(e)}")
21
+ model = None
22
+
23
+ def detect_potholes_and_cracks(frame):
24
+ if model is None:
25
+ logging.error("YOLO model not loaded. Skipping pothole and crack detection.")
26
+ return [], frame
27
+
28
+ try:
29
+ results = model(frame)
30
+ except Exception as e:
31
+ logging.error(f"Error during YOLO inference: {str(e)}")
32
+ return [], frame
33
+
34
+ detections = []
35
+ line_counter = 1
36
+
37
+ for r in results:
38
+ for box in r.boxes:
39
+ conf = float(box.conf[0])
40
+ if conf < 0.5:
41
+ continue
42
+ cls = int(box.cls[0])
43
+ label = model.names[cls]
44
+ if label not in ["crack", "pothole", "debris"]:
45
+ continue
46
+ xyxy = box.xyxy[0).cpu().numpy().astype(int)
47
+ x_min, y_min, x_max, y_max = xyxy
48
+
49
+ severity = None
50
+ if label == "crack":
51
+ severity = (255, 0, 0) # Red
52
+ severity = random.choice(["low", "medium", "high"])
53
+ elif label == "pothole":
54
+ color = (0, 255, 0) # Green
55
+ else: # debris
56
+ color = (0, 0, 255) # Blue
57
+
58
+ detection_label = f"Line {line_counter} - {label.capitalize()} (Conf: {conf:.2f})"
59
+ item = {
60
+ "type": label,
61
+ "label": detection_label,
62
+ "confidence": conf,
63
+ "coordinates": [x_min, y_min, x_max, y_max]
64
+ }
65
+ if severity:
66
+ item["severity"] = severity
67
+
68
+ detections.append(item)
69
+
70
+ cv2.rectangle(frame, (x_min, y_min), (x_max, y_max), color, 2)
71
+ cv2.putText(frame, detection_label, (x_min, y_min - 10),
72
+ cv2.FONT_HERSHEY_SIMPLEXSIMPLEX, 0.6, color, 2)
73
+
74
+ line_counter += 1
75
+
76
+ logging.info(f"Detected {len(detections)} potholes/cracks in road_safety.")
77
+ return detections, frame