lokesh341 commited on
Commit
15507ed
·
1 Parent(s): a865916

Update services/operations_maintenance/crack_detection.py

Browse files
services/operations_maintenance/crack_detection.py CHANGED
@@ -1,76 +1,54 @@
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 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
- # Validate input frame
31
- if not isinstance(frame, np.ndarray) or frame.size == 0:
32
- logging.error("Invalid input frame provided to crack_detection.")
33
- return []
34
-
35
- # Check if model is loaded
36
- if model is None:
37
- logging.error("YOLO model not loaded. Skipping crack detection.")
38
- return []
39
-
40
  try:
41
- # Perform YOLO inference
42
- results = model(frame, verbose=False)
43
- logging.debug("Completed YOLO inference for crack detection.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  except Exception as e:
45
- logging.error(f"Error during YOLO inference: {str(e)}")
46
- return []
47
-
48
- detections: List[Dict[str, Any]] = []
49
- line_counter = 1
50
-
51
- for r in results:
52
- for box in r.boxes:
53
- conf = float(box.conf[0])
54
- if conf < 0.3:
55
- continue
56
- cls = int(box.cls[0])
57
- label = model.names[cls]
58
- if label != "crack":
59
- continue
60
- xyxy = box.xyxy[0].cpu().numpy().astype(int)
61
- x_min, y_min, x_max, y_max = xyxy
62
-
63
- severity = random.choice(["low", "medium", "high"])
64
- detection_label = f"Line {line_counter} - {label.capitalize()} (Conf: {conf:.2f})"
65
- detections.append({
66
- "type": label,
67
- "label": detection_label,
68
- "confidence": conf,
69
- "coordinates": [x_min, y_min, x_max, y_max],
70
- "severity": severity
71
- })
72
-
73
- line_counter += 1
74
-
75
- logging.info(f"Detected {len(detections)} cracks in operations_maintenance.")
76
- return detections
 
1
  import cv2
2
  import numpy as np
 
 
 
3
  import logging
4
+ from typing import List, Dict, Any, Tuple
5
+ from ultralytics import YOLO
6
 
7
+ # Setup logging
8
  logging.basicConfig(
9
  filename="app.log",
10
  level=logging.INFO,
11
  format="%(asctime)s - %(levelname)s - %(message)s"
12
  )
13
 
14
+ def detect_cracks_and_holes(frame: np.ndarray) -> Tuple[List[Dict[str, Any]], np.ndarray]:
15
+ """
16
+ Detect cracks and holes in a frame using YOLO.
17
+ Args:
18
+ frame: Input frame (numpy array)
19
+ Returns:
20
+ tuple: List of detected items (dicts with type, box, severity, etc.) and the input frame
21
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  try:
23
+ # Load YOLO model
24
+ model = YOLO("models/yolov8m.pt")
25
+ # Run inference
26
+ results = model(frame)
27
+
28
+ detections: List[Dict[str, Any]] = []
29
+ line_counter = 1
30
+
31
+ for result in results:
32
+ boxes = result.boxes.xyxy.cpu().numpy()
33
+ confidences = result.boxes.conf.cpu().numpy()
34
+ classes = result.boxes.cls.cpu().numpy()
35
+
36
+ for box, conf, cls in zip(boxes, confidences, classes):
37
+ x_min, y_min, x_max, y_max = map(int, box)
38
+ type_ = "crack" if cls == 0 else "hole" # Assume class 0=crack, 1=hole
39
+ severity = "Severe" if conf > 0.8 else "Moderate" if conf > 0.5 else "Minor"
40
+ label = f"Line {line_counter} - {type_.capitalize()} ({severity})"
41
+ detections.append({
42
+ "type": type_,
43
+ "label": label,
44
+ "box": [x_min, y_min, x_max, y_max],
45
+ "severity": severity,
46
+ "confidence": float(conf)
47
+ })
48
+ line_counter += 1
49
+
50
+ logging.info(f"Detected {len(detections)} cracks/holes in frame.")
51
+ return detections, frame
52
  except Exception as e:
53
+ logging.error(f"Error detecting cracks/holes: {str(e)}")
54
+ return [], frame