lokesh341 commited on
Commit
185810d
·
1 Parent(s): 51c44a6

Update services/detection_service.py

Browse files
Files changed (1) hide show
  1. services/detection_service.py +32 -54
services/detection_service.py CHANGED
@@ -1,8 +1,7 @@
1
  import cv2
2
  import numpy as np
3
- from ultralytics import YOLO
4
- import os
5
  import logging
 
6
 
7
  # Setup logging
8
  logging.basicConfig(
@@ -11,63 +10,42 @@ logging.basicConfig(
11
  format="%(asctime)s - %(levelname)s - %(message)s"
12
  )
13
 
14
- # Load YOLOv8m model for generic detection
15
- BASE_DIR = os.path.dirname(os.path.abspath(__file__))
16
- MODEL_PATH = os.path.abspath(os.path.join(BASE_DIR, "../models/yolov8m.pt"))
17
- try:
18
- model = YOLO(MODEL_PATH)
19
- logging.info("Loaded YOLOv8m model for generic detection.")
20
- except Exception as e:
21
- logging.error(f"Failed to load YOLOv8m model: {str(e)}")
22
- model = None
23
-
24
- def process_frame(frame):
25
  """
26
- Process a frame for generic object detection using YOLOv8m.
27
  Args:
28
  frame: Input frame (numpy array)
29
  Returns:
30
- list: List of detected objects
31
- numpy array: Annotated frame with numbered labels
32
  """
33
- if model is None:
34
- logging.error("YOLO model not loaded. Skipping generic detection.")
35
- return [], frame
36
-
37
  try:
 
38
  results = model(frame)
39
- except Exception as e:
40
- logging.error(f"Error during YOLO inference: {str(e)}")
41
- return [], frame
42
 
43
- detections = []
44
- line_counter = 1 # Initialize counter for numbered labels
45
-
46
- for r in results:
47
- for box in r.boxes:
48
- conf = float(box.conf[0])
49
- if conf < 0.5:
50
- continue
51
- cls = int(box.cls[0])
52
- label = model.names[cls]
53
- xyxy = box.xyxy[0].cpu().numpy()
54
- x_min, y_min, x_max, y_max = map(int, xyxy)
55
-
56
- # Add numbered label
57
- detection_label = f"Line {line_counter} - {label.capitalize()} (Conf: {conf:.2f})"
58
- detections.append({
59
- "type": label,
60
- "label": detection_label,
61
- "confidence": conf,
62
- "coordinates": [x_min, y_min, x_max, y_max]
63
- })
64
-
65
- # Draw bounding box and label
66
- color = (0, 255, 255) # Yellow for generic detections
67
- cv2.rectangle(frame, (x_min, y_min), (x_max, y_max), color, 2)
68
- cv2.putText(frame, detection_label, (x_min, y_min - 10),
69
- cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
70
-
71
- line_counter += 1
72
-
73
- return detections, frame
 
1
  import cv2
2
  import numpy as np
 
 
3
  import logging
4
+ from ultralytics import YOLO
5
 
6
  # Setup logging
7
  logging.basicConfig(
 
10
  format="%(asctime)s - %(levelname)s - %(message)s"
11
  )
12
 
13
+ def process_frame(frame: np.ndarray) -> tuple[list[dict[str, any]], np.ndarray]:
 
 
 
 
 
 
 
 
 
 
14
  """
15
+ Process a frame using YOLO model to detect cracks and holes.
16
  Args:
17
  frame: Input frame (numpy array)
18
  Returns:
19
+ tuple: List of detected items and annotated frame
 
20
  """
 
 
 
 
21
  try:
22
+ model = YOLO("models/yolov8m.pt")
23
  results = model(frame)
 
 
 
24
 
25
+ detections = []
26
+ line_counter = 1
27
+
28
+ for result in results:
29
+ boxes = result.boxes.xyxy.cpu().numpy()
30
+ confidences = result.boxes.conf.cpu().numpy()
31
+ classes = result.boxes.cls.cpu().numpy()
32
+
33
+ for box, conf, cls in zip(boxes, confidences, classes):
34
+ x_min, y_min, x_max, y_max = map(int, box)
35
+ type_ = "crack" if cls == 0 else "hole" # Assume class 0=crack, 1=hole
36
+ severity = "Severe" if conf > 0.8 else "Moderate" if conf > 0.5 else "Minor"
37
+ label = f"Line {line_counter} - {type_.capitalize()} ({severity})"
38
+ detections.append({
39
+ "type": type_,
40
+ "label": label,
41
+ "box": [x_min, y_min, x_max, y_max],
42
+ "severity": severity,
43
+ "confidence": float(conf)
44
+ })
45
+ line_counter += 1
46
+
47
+ logging.info(f"Detected {len(detections)} objects in frame.")
48
+ return detections, frame
49
+ except Exception as e:
50
+ logging.error(f"Error processing frame: {str(e)}")
51
+ return [], frame