lokesh341 commited on
Commit
fd3b717
·
1 Parent(s): 9ef90b7

Update services/crack_detection_service.py

Browse files
Files changed (1) hide show
  1. services/crack_detection_service.py +56 -67
services/crack_detection_service.py CHANGED
@@ -1,70 +1,59 @@
1
  import cv2
2
  import numpy as np
3
-
4
- def detect_cracks_and_holes(frame):
5
- try:
6
- # Convert frame to grayscale
7
- gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
8
- blurred = cv2.GaussianBlur(gray, (5, 5), 0)
9
-
10
- # Edge detection using Canny
11
- edges = cv2.Canny(blurred, 30, 100) # Lower thresholds to detect more cracks
12
-
13
- # Morphological operations to enhance cracks and holes
14
- kernel = np.ones((3, 3), np.uint8)
15
- dilated = cv2.dilate(edges, kernel, iterations=2)
16
- eroded = cv2.erode(dilated, kernel, iterations=1)
17
-
18
- # Find contours
19
- contours, _ = cv2.findContours(eroded, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
20
-
21
- items = []
22
- for contour in contours:
23
- # Filter small contours (noise)
24
- area = cv2.contourArea(contour)
25
- if area < 30: # Reduced threshold to catch smaller cracks
 
 
 
 
 
26
  continue
27
-
28
- # Get bounding box
29
- x, y, w, h = cv2.boundingRect(contour)
30
- area = w * h
31
-
32
- # Calculate aspect ratio and circularity
33
- aspect_ratio = float(w) / h if h > 0 else 0
34
- perimeter = cv2.arcLength(contour, True)
35
- circularity = 4 * np.pi * area / (perimeter * perimeter) if perimeter > 0 else 0
36
-
37
- # Classify as crack or hole
38
- if 0.05 < aspect_ratio < 20 and circularity < 0.4: # Adjusted for more crack detection
39
- item_type = 'crack'
40
- # Check if it's an underlying crack (longer and thinner)
41
- if aspect_ratio > 8:
42
- severity = 'Underlying'
43
- elif area > 4000:
44
- severity = 'Severe'
45
- elif area > 800:
46
- severity = 'Moderate'
47
- else:
48
- severity = 'Minor'
49
- elif circularity > 0.6: # Circular shapes are holes
50
- item_type = 'hole'
51
- if area > 4000:
52
- severity = 'Severe'
53
- elif area > 800:
54
- severity = 'Moderate'
55
- else:
56
- severity = 'Minor'
57
- else:
58
- continue # Skip objects that don't match crack or hole criteria
59
-
60
- items.append({
61
- 'type': item_type,
62
- 'box': [x, y, x + w, y + h],
63
- 'severity': severity,
64
- 'confidence': 0.95 # Simulated confidence
65
- })
66
-
67
- return items
68
- except Exception as e:
69
- print(f"Error in detection: {str(e)}")
70
- return []
 
1
  import cv2
2
  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.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