lokesh341 commited on
Commit
c45c8a6
·
1 Parent(s): b5f5a04

Update services/operations_maintenance/crack_detection.py

Browse files
services/operations_maintenance/crack_detection.py CHANGED
@@ -3,57 +3,83 @@ import numpy as np
3
  from ultralytics import YOLO
4
  import os
5
  import random
 
 
6
 
7
- # Load YOLOv8m-seg model for crack detection
 
 
 
 
 
 
 
8
  BASE_DIR = os.path.dirname(os.path.abspath(__file__))
9
- MODEL_PATH = os.path.abspath(os.path.join(BASE_DIR, "../../models/yolov8m-seg.pt"))
10
- model = YOLO(MODEL_PATH)
 
 
 
 
 
 
 
 
11
 
12
- def detect_cracks_and_objects(frame):
13
  """
14
- Detect cracks and other objects in a frame using YOLOv8m-seg.
 
15
  Args:
16
- frame: Input frame (numpy array)
 
17
  Returns:
18
- list: List of detected items with type, label, coordinates, confidence, and severity
19
  """
20
- # Run YOLOv8 inference
21
- results = model(frame)
 
 
22
 
23
- detected_items = []
24
- line_counter = 1 # Initialize counter for numbered labels
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- # Process detections
27
  for r in results:
28
  for box in r.boxes:
29
  conf = float(box.conf[0])
30
- if conf < 0.5:
31
  continue
32
  cls = int(box.cls[0])
33
  label = model.names[cls]
34
- if label not in ["crack", "pothole", "object"]: # Assuming these classes exist
35
  continue
36
- xyxy = box.xyxy[0].cpu().numpy()
37
- x_min, y_min, x_max, y_max = map(int, xyxy)
38
-
39
- # Simulate severity for cracks
40
- severity = None
41
- if label == "crack":
42
- severity = random.choice(["low", "medium", "high"])
43
-
44
- # Add numbered label
45
  detection_label = f"Line {line_counter} - {label.capitalize()} (Conf: {conf:.2f})"
46
- item = {
47
  "type": label,
48
  "label": detection_label,
49
  "confidence": conf,
50
- "coordinates": [x_min, y_min, x_max, y_max]
51
- }
52
- if severity:
53
- item["severity"] = severity
54
-
55
- detected_items.append(item)
56
 
57
  line_counter += 1
58
 
59
- return detected_items
 
 
3
  from ultralytics import YOLO
4
  import os
5
  import random
6
+ import logging
7
+ from typing import 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.pt"))
19
+
20
+ # Initialize YOLO model
21
+ try:
22
+ model = YOLO(MODEL_PATH)
23
+ logging.info("Loaded YOLOv8m model for crack detection.")
24
+ logging.info(f"Model class names: {model.names}")
25
+ except Exception as e:
26
+ logging.error(f"Failed to load YOLOv8m model: {str(e)}")
27
+ model = None
28
 
29
+ def detect_cracks_and_objects(frame: np.ndarray) -> List[Dict[str, Any]]:
30
  """
31
+ Detect cracks and other objects in a video frame using YOLOv8m.
32
+
33
  Args:
34
+ frame (np.ndarray): Input frame in BGR format.
35
+
36
  Returns:
37
+ List[Dict[str, Any]]: List of detected items with type, label, confidence, coordinates, and severity.
38
  """
39
+ # Validate input frame
40
+ if not isinstance(frame, np.ndarray) or frame.size == 0:
41
+ logging.error("Invalid input frame provided to crack_detection.")
42
+ return []
43
 
44
+ # Check if model is loaded
45
+ if model is None:
46
+ logging.error("YOLO model not loaded. Skipping crack detection.")
47
+ return []
48
+
49
+ try:
50
+ # Perform YOLO inference
51
+ results = model(frame, verbose=False)
52
+ logging.debug("Completed YOLO inference for crack detection.")
53
+ except Exception as e:
54
+ logging.error(f"Error during YOLO inference: {str(e)}")
55
+ return []
56
+
57
+ detections: List[Dict[str, Any]] = []
58
+ line_counter = 1
59
 
 
60
  for r in results:
61
  for box in r.boxes:
62
  conf = float(box.conf[0])
63
+ if conf < 0.3:
64
  continue
65
  cls = int(box.cls[0])
66
  label = model.names[cls]
67
+ if label != "crack":
68
  continue
69
+ xyxy = box.xyxy[0].cpu().numpy().astype(int)
70
+ x_min, y_min, x_max, y_max = xyxy
71
+
72
+ severity = random.choice(["low", "medium", "high"])
 
 
 
 
 
73
  detection_label = f"Line {line_counter} - {label.capitalize()} (Conf: {conf:.2f})"
74
+ detections.append({
75
  "type": label,
76
  "label": detection_label,
77
  "confidence": conf,
78
+ "coordinates": [x_min, y_min, x_max, y_max],
79
+ "severity": severity
80
+ })
 
 
 
81
 
82
  line_counter += 1
83
 
84
+ logging.info(f"Detected {len(detections)} cracks in operations_maintenance.")
85
+ return detections