lokesh341 commited on
Commit
ebb854e
·
1 Parent(s): f1cdb98

Update services/under_construction/earthwork_detection.py

Browse files
services/under_construction/earthwork_detection.py CHANGED
@@ -3,40 +3,65 @@ import numpy as np
3
  from ultralytics import YOLO
4
  import os
5
  import logging
 
6
 
 
7
  logging.basicConfig(
8
  filename="app.log",
9
  level=logging.INFO,
10
  format="%(asctime)s - %(levelname)s - %(message)s"
11
  )
12
 
 
13
  BASE_DIR = os.path.dirname(os.path.abspath(__file__))
14
- MODEL_PATH = os.path.abspath(os.path.join(BASE_DIR, "../../models/yolov8m.pt"))
 
 
15
  try:
16
  model = YOLO(MODEL_PATH)
17
- logging.info("Loaded YOLOv8m model for earthwork detection.")
 
18
  except Exception as e:
19
- logging.error(f"Failed to load YOLOv8m model: {str(e)}")
20
  model = None
21
 
22
- def process_earthwork(frame):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  if model is None:
24
  logging.error("YOLO model not loaded. Skipping earthwork detection.")
25
  return [], frame
26
 
27
  try:
28
- results = model(frame)
 
 
29
  except Exception as e:
30
  logging.error(f"Error during YOLO inference: {str(e)}")
31
  return [], frame
32
 
33
- detections = []
34
  line_counter = 1
35
 
36
  for r in results:
37
  for box in r.boxes:
38
  conf = float(box.conf[0])
39
- if conf < 0.5:
40
  continue
41
  cls = int(box.cls[0])
42
  label = model.names[cls]
@@ -53,12 +78,19 @@ def process_earthwork(frame):
53
  "coordinates": [x_min, y_min, x_max, y_max]
54
  })
55
 
56
- color = (255, 165, 0) # Orange as requested
57
  cv2.rectangle(frame, (x_min, y_min), (x_max, y_max), color, 2)
58
- cv2.putText(frame, detection_label, (x_min, y_min - 10),
59
- cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
 
 
 
 
 
 
 
60
 
61
  line_counter += 1
62
 
63
- logging.info(f"Detected {len(detections)} earthwork activities in under_construction.")
64
  return detections, frame
 
3
  from ultralytics import YOLO
4
  import os
5
  import logging
6
+ from typing import Tuple, List, Dict, Any
7
 
8
+ # Configure logging
9
  logging.basicConfig(
10
  filename="app.log",
11
  level=logging.INFO,
12
  format="%(asctime)s - %(levelname)s - %(message)s"
13
  )
14
 
15
+ # Define base directory and model path
16
  BASE_DIR = os.path.dirname(os.path.abspath(__file__))
17
+ MODEL_PATH = os.path.abspath(os.path.join(BASE_DIR, "../../models/yolov8n.pt"))
18
+
19
+ # Initialize YOLO model
20
  try:
21
  model = YOLO(MODEL_PATH)
22
+ logging.info("Loaded YOLOv8n model for earthwork detection.")
23
+ logging.info(f"Model class names: {model.names}")
24
  except Exception as e:
25
+ logging.error(f"Failed to load YOLOv8n model: {str(e)}")
26
  model = None
27
 
28
+ def process_earthwork(frame: np.ndarray) -> Tuple[List[Dict[str, Any]], np.ndarray]:
29
+ """
30
+ Detect earthwork-related objects in a video frame using YOLOv8n.
31
+
32
+ Args:
33
+ frame (np.ndarray): Input frame in BGR format.
34
+
35
+ Returns:
36
+ Tuple[List[Dict[str, Any]], np.ndarray]: A tuple containing:
37
+ - List of detected earthwork items.
38
+ - Annotated frame with bounding boxes and labels.
39
+ """
40
+ # Validate input frame
41
+ if not isinstance(frame, np.ndarray) or frame.size == 0:
42
+ logging.error("Invalid input frame provided to earthwork_detection.")
43
+ return [], frame
44
+
45
+ # Check if model is loaded
46
  if model is None:
47
  logging.error("YOLO model not loaded. Skipping earthwork detection.")
48
  return [], frame
49
 
50
  try:
51
+ # Perform YOLO inference
52
+ results = model(frame, verbose=False)
53
+ logging.debug("Completed YOLO inference for earthwork detection.")
54
  except Exception as e:
55
  logging.error(f"Error during YOLO inference: {str(e)}")
56
  return [], frame
57
 
58
+ detections: List[Dict[str, Any]] = []
59
  line_counter = 1
60
 
61
  for r in results:
62
  for box in r.boxes:
63
  conf = float(box.conf[0])
64
+ if conf < 0.3:
65
  continue
66
  cls = int(box.cls[0])
67
  label = model.names[cls]
 
78
  "coordinates": [x_min, y_min, x_max, y_max]
79
  })
80
 
81
+ color = (255, 165, 0) # Orange for earthwork
82
  cv2.rectangle(frame, (x_min, y_min), (x_max, y_max), color, 2)
83
+ cv2.putText(
84
+ frame,
85
+ detection_label,
86
+ (x_min, y_min - 10),
87
+ cv2.FONT_HERSHEY_SIMPLEX,
88
+ 0.6,
89
+ color,
90
+ 2
91
+ )
92
 
93
  line_counter += 1
94
 
95
+ logging.info(f"Detected {len(detections)} earthwork items in under_construction.")
96
  return detections, frame