lokesh341 commited on
Commit
b9160f0
·
verified ·
1 Parent(s): 026ced7

Update services/operations_maintenance/crack_detection.py

Browse files
services/operations_maintenance/crack_detection.py CHANGED
@@ -1,54 +1,58 @@
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import cv2
2
  import numpy as np
3
+ from typing import List, Tuple, Dict, Any
 
 
 
 
 
 
 
 
 
4
 
5
  def detect_cracks_and_holes(frame: np.ndarray) -> Tuple[List[Dict[str, Any]], np.ndarray]:
6
  """
7
+ Detect cracks and holes in the frame using edge detection and contour analysis.
8
  Args:
9
+ frame: Input frame as a numpy array.
10
  Returns:
11
+ Tuple of (list of detections, annotated frame).
12
  """
13
+ # Convert to grayscale
14
+ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
15
+
16
+ # Apply Gaussian blur to reduce noise
17
+ blurred = cv2.GaussianBlur(gray, (5, 5), 0)
18
+
19
+ # Edge detection using Canny
20
+ edges = cv2.Canny(blurred, 50, 150)
21
+
22
+ # Dilate edges to connect nearby edges
23
+ kernel = np.ones((3, 3), np.uint8)
24
+ dilated = cv2.dilate(edges, kernel, iterations=1)
25
+
26
+ # Find contours
27
+ contours, _ = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
28
+
29
+ detections = []
30
+ for i, contour in enumerate(contours):
31
+ # Calculate the area of the contour
32
+ area = cv2.contourArea(contour)
33
+ if area < 100: # Ignore small contours
34
+ continue
35
+
36
+ # Get bounding box
37
+ x, y, w, h = cv2.boundingRect(contour)
38
+ x_min, y_min, x_max, y_max = x, y, x + w, y + h
39
+
40
+ # Determine if it's a crack or hole based on shape and area
41
+ perimeter = cv2.arcLength(contour, True)
42
+ circularity = 4 * np.pi * area / (perimeter * perimeter) if perimeter > 0 else 0
43
+
44
+ # Classify as hole if more circular, crack if elongated
45
+ dtype = "hole" if circularity > 0.5 else "crack"
46
+ label = f"{dtype.capitalize()} {i+1}"
47
+
48
+ # Determine severity based on area
49
+ severity = "Severe" if area > 1000 else "Moderate" if area > 500 else "Mild"
50
+
51
+ detections.append({
52
+ "box": [x_min, y_min, x_max, y_max],
53
+ "label": label,
54
+ "type": dtype,
55
+ "severity": severity
56
+ })
57
+
58
+ return detections, frame