Spaces:
Running
on
Zero
Running
on
Zero
Delete visualization_helper.py
Browse files- visualization_helper.py +0 -147
visualization_helper.py
DELETED
@@ -1,147 +0,0 @@
|
|
1 |
-
import cv2
|
2 |
-
import numpy as np
|
3 |
-
import matplotlib.pyplot as plt
|
4 |
-
from typing import Any, List, Dict, Tuple, Optional
|
5 |
-
import io
|
6 |
-
from PIL import Image
|
7 |
-
|
8 |
-
class VisualizationHelper:
|
9 |
-
"""Helper class for visualizing detection results"""
|
10 |
-
|
11 |
-
@staticmethod
|
12 |
-
def visualize_detection(image: Any, result: Any, color_mapper: Optional[Any] = None,
|
13 |
-
figsize: Tuple[int, int] = (12, 12),
|
14 |
-
return_pil: bool = False) -> Optional[Image.Image]:
|
15 |
-
"""
|
16 |
-
Visualize detection results on a single image
|
17 |
-
|
18 |
-
Args:
|
19 |
-
image: Image path or numpy array
|
20 |
-
result: Detection result object
|
21 |
-
color_mapper: ColorMapper instance for consistent colors
|
22 |
-
figsize: Figure size
|
23 |
-
return_pil: If True, returns a PIL Image object
|
24 |
-
|
25 |
-
Returns:
|
26 |
-
PIL Image if return_pil is True, otherwise displays the plot
|
27 |
-
"""
|
28 |
-
if result is None:
|
29 |
-
print('No data for visualization')
|
30 |
-
return None
|
31 |
-
|
32 |
-
# Read image if path is provided
|
33 |
-
if isinstance(image, str):
|
34 |
-
img = cv2.imread(image)
|
35 |
-
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
36 |
-
else:
|
37 |
-
img = image
|
38 |
-
if len(img.shape) == 3 and img.shape[2] == 3:
|
39 |
-
# Check if BGR format (OpenCV) and convert to RGB if needed
|
40 |
-
if isinstance(img, np.ndarray):
|
41 |
-
# Assuming BGR format from OpenCV
|
42 |
-
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
43 |
-
|
44 |
-
# Create figure
|
45 |
-
fig, ax = plt.subplots(figsize=figsize)
|
46 |
-
ax.imshow(img)
|
47 |
-
|
48 |
-
# Get bounding boxes, classes and confidences
|
49 |
-
boxes = result.boxes.xyxy.cpu().numpy()
|
50 |
-
classes = result.boxes.cls.cpu().numpy()
|
51 |
-
confs = result.boxes.conf.cpu().numpy()
|
52 |
-
|
53 |
-
# Get class names
|
54 |
-
names = result.names
|
55 |
-
|
56 |
-
# Create a default color mapper if none is provided
|
57 |
-
if color_mapper is None:
|
58 |
-
# For backward compatibility, fallback to a simple color function
|
59 |
-
from matplotlib import colormaps
|
60 |
-
cmap = colormaps['tab10']
|
61 |
-
def get_color(class_id):
|
62 |
-
return cmap(class_id % 10)
|
63 |
-
else:
|
64 |
-
# Use the provided color mapper
|
65 |
-
def get_color(class_id):
|
66 |
-
hex_color = color_mapper.get_color(class_id)
|
67 |
-
# Convert hex to RGB float values for matplotlib
|
68 |
-
hex_color = hex_color.lstrip('#')
|
69 |
-
return tuple(int(hex_color[i:i+2], 16) / 255 for i in (0, 2, 4)) + (1.0,)
|
70 |
-
|
71 |
-
# Draw detection results
|
72 |
-
for box, cls, conf in zip(boxes, classes, confs):
|
73 |
-
x1, y1, x2, y2 = box
|
74 |
-
cls_id = int(cls)
|
75 |
-
cls_name = names[cls_id]
|
76 |
-
|
77 |
-
# Get color for this class
|
78 |
-
box_color = get_color(cls_id)
|
79 |
-
|
80 |
-
# Add text label with colored background
|
81 |
-
ax.text(x1, y1 - 5, f'{cls_name}: {conf:.2f}',
|
82 |
-
color='white', fontsize=10,
|
83 |
-
bbox=dict(facecolor=box_color[:3], alpha=0.7))
|
84 |
-
|
85 |
-
# Add bounding box
|
86 |
-
ax.add_patch(plt.Rectangle((x1, y1), x2-x1, y2-y1,
|
87 |
-
fill=False, edgecolor=box_color[:3], linewidth=2))
|
88 |
-
|
89 |
-
ax.axis('off')
|
90 |
-
# ax.set_title('Detection Result')
|
91 |
-
plt.tight_layout()
|
92 |
-
|
93 |
-
if return_pil:
|
94 |
-
# Convert plot to PIL Image
|
95 |
-
buf = io.BytesIO()
|
96 |
-
fig.savefig(buf, format='png', bbox_inches='tight', pad_inches=0)
|
97 |
-
buf.seek(0)
|
98 |
-
pil_img = Image.open(buf)
|
99 |
-
plt.close(fig)
|
100 |
-
return pil_img
|
101 |
-
else:
|
102 |
-
plt.show()
|
103 |
-
return None
|
104 |
-
|
105 |
-
@staticmethod
|
106 |
-
def create_summary(result: Any) -> Dict:
|
107 |
-
"""
|
108 |
-
Create a summary of detection results
|
109 |
-
|
110 |
-
Args:
|
111 |
-
result: Detection result object
|
112 |
-
|
113 |
-
Returns:
|
114 |
-
Dictionary with detection summary statistics
|
115 |
-
"""
|
116 |
-
if result is None:
|
117 |
-
return {"error": "No detection result provided"}
|
118 |
-
|
119 |
-
# Get classes and confidences
|
120 |
-
classes = result.boxes.cls.cpu().numpy().astype(int)
|
121 |
-
confidences = result.boxes.conf.cpu().numpy()
|
122 |
-
names = result.names
|
123 |
-
|
124 |
-
# Count detections by class
|
125 |
-
class_counts = {}
|
126 |
-
for cls, conf in zip(classes, confidences):
|
127 |
-
cls_name = names[int(cls)]
|
128 |
-
if cls_name not in class_counts:
|
129 |
-
class_counts[cls_name] = {"count": 0, "confidences": []}
|
130 |
-
|
131 |
-
class_counts[cls_name]["count"] += 1
|
132 |
-
class_counts[cls_name]["confidences"].append(float(conf))
|
133 |
-
|
134 |
-
# Calculate average confidence for each class
|
135 |
-
for cls_name, stats in class_counts.items():
|
136 |
-
if stats["confidences"]:
|
137 |
-
stats["average_confidence"] = float(np.mean(stats["confidences"]))
|
138 |
-
stats.pop("confidences") # Remove detailed confidences list to keep summary concise
|
139 |
-
|
140 |
-
# Prepare summary
|
141 |
-
summary = {
|
142 |
-
"total_objects": len(classes),
|
143 |
-
"class_counts": class_counts,
|
144 |
-
"unique_classes": len(class_counts)
|
145 |
-
}
|
146 |
-
|
147 |
-
return summary
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|