Spaces:
Runtime error
Runtime error
Update services/under_construction/bridge_pier_check.py
Browse files
services/under_construction/bridge_pier_check.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/
|
|
|
|
|
15 |
try:
|
16 |
model = YOLO(MODEL_PATH)
|
17 |
-
logging.info("Loaded
|
|
|
18 |
except Exception as e:
|
19 |
-
logging.error(f"Failed to load
|
20 |
model = None
|
21 |
|
22 |
-
def process_bridge_piers(frame):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
if model is None:
|
24 |
-
logging.error("YOLO model not loaded. Skipping bridge pier
|
25 |
return [], frame
|
26 |
|
27 |
try:
|
28 |
-
|
|
|
|
|
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.
|
40 |
continue
|
41 |
cls = int(box.cls[0])
|
42 |
label = model.names[cls]
|
@@ -45,18 +70,25 @@ def process_bridge_piers(frame):
|
|
45 |
xyxy = box.xyxy[0].cpu().numpy().astype(int)
|
46 |
x_min, y_min, x_max, y_max = xyxy
|
47 |
|
48 |
-
detection_label = f"Line {line_counter} -
|
49 |
detections.append({
|
50 |
-
"type":
|
51 |
"label": detection_label,
|
52 |
"confidence": conf,
|
53 |
"coordinates": [x_min, y_min, x_max, y_max]
|
54 |
})
|
55 |
|
56 |
-
color = (255,
|
57 |
cv2.rectangle(frame, (x_min, y_min), (x_max, y_max), color, 2)
|
58 |
-
cv2.putText(
|
59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
|
61 |
line_counter += 1
|
62 |
|
|
|
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 bridge pier 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_bridge_piers(frame: np.ndarray) -> Tuple[List[Dict[str, Any]], np.ndarray]:
|
29 |
+
"""
|
30 |
+
Detect bridge piers 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 bridge piers.
|
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 bridge_pier_check.")
|
43 |
+
return [], frame
|
44 |
+
|
45 |
+
# Check if model is loaded
|
46 |
if model is None:
|
47 |
+
logging.error("YOLO model not loaded. Skipping bridge pier detection.")
|
48 |
return [], frame
|
49 |
|
50 |
try:
|
51 |
+
# Perform YOLO inference
|
52 |
+
results = model(frame, verbose=False)
|
53 |
+
logging.debug("Completed YOLO inference for bridge pier 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]
|
|
|
70 |
xyxy = box.xyxy[0].cpu().numpy().astype(int)
|
71 |
x_min, y_min, x_max, y_max = xyxy
|
72 |
|
73 |
+
detection_label = f"Line {line_counter} - {label.capitalize()} (Conf: {conf:.2f})"
|
74 |
detections.append({
|
75 |
+
"type": label,
|
76 |
"label": detection_label,
|
77 |
"confidence": conf,
|
78 |
"coordinates": [x_min, y_min, x_max, y_max]
|
79 |
})
|
80 |
|
81 |
+
color = (255, 165, 0) # Orange for bridge piers
|
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 |
|