Spaces:
Runtime error
Runtime error
Update services/shadow_detection.py
Browse files- services/shadow_detection.py +49 -36
services/shadow_detection.py
CHANGED
@@ -1,45 +1,58 @@
|
|
1 |
-
# services/shadow_detection.py
|
2 |
import cv2
|
3 |
import numpy as np
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
def detect_shadows(frame):
|
6 |
"""
|
7 |
-
Detect shadows in a frame using
|
8 |
Args:
|
9 |
frame: Input frame (numpy array)
|
10 |
Returns:
|
11 |
-
dict:
|
12 |
-
numpy array: Annotated frame
|
13 |
"""
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
"
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import cv2
|
2 |
import numpy as np
|
3 |
+
import logging
|
4 |
+
|
5 |
+
# Setup logging
|
6 |
+
logging.basicConfig(
|
7 |
+
filename="app.log",
|
8 |
+
level=logging.INFO,
|
9 |
+
format="%(asctime)s - %(levelname)s - %(message)s"
|
10 |
+
)
|
11 |
|
12 |
def detect_shadows(frame):
|
13 |
"""
|
14 |
+
Detect shadows in a frame using brightness thresholding.
|
15 |
Args:
|
16 |
frame: Input frame (numpy array)
|
17 |
Returns:
|
18 |
+
dict: Results with detections and annotated frame
|
|
|
19 |
"""
|
20 |
+
try:
|
21 |
+
# Convert to grayscale
|
22 |
+
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
23 |
+
|
24 |
+
# Threshold to detect dark areas (shadows)
|
25 |
+
_, shadow_mask = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY_INV)
|
26 |
+
contours, _ = cv2.findContours(shadow_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
27 |
+
|
28 |
+
detections = []
|
29 |
+
line_counter = 1 # Initialize counter for numbered labels
|
30 |
+
|
31 |
+
for contour in contours:
|
32 |
+
area = cv2.contourArea(contour)
|
33 |
+
if area < 500: # Filter small areas
|
34 |
+
continue
|
35 |
+
x, y, w, h = cv2.boundingRect(contour)
|
36 |
+
x_min, y_min, x_max, y_max = x, y, x + w, y + h
|
37 |
+
|
38 |
+
# Add numbered label
|
39 |
+
detection_label = f"Line {line_counter} - Shadow"
|
40 |
+
detections.append({
|
41 |
+
"type": "shadow",
|
42 |
+
"label": detection_label,
|
43 |
+
"coordinates": [x_min, y_min, x_max, y_max]
|
44 |
+
})
|
45 |
+
|
46 |
+
# Draw bounding box and label
|
47 |
+
color = (128, 128, 128) # Gray for shadows
|
48 |
+
cv2.rectangle(frame, (x_min, y_min), (x_max, y_max), color, 2)
|
49 |
+
cv2.putText(frame, detection_label, (x_min, y_min - 10),
|
50 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
|
51 |
+
|
52 |
+
line_counter += 1
|
53 |
+
|
54 |
+
logging.info(f"Detected {len(detections)} shadows in frame.")
|
55 |
+
return {"detections": detections, "frame": frame}
|
56 |
+
except Exception as e:
|
57 |
+
logging.error(f"Error detecting shadows: {str(e)}")
|
58 |
+
return {"detections": [], "frame": frame}
|