-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_optimizations.py
More file actions
169 lines (135 loc) Β· 5.8 KB
/
test_optimizations.py
File metadata and controls
169 lines (135 loc) Β· 5.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#!/usr/bin/env python3
"""
Quick test script to demonstrate optimization performance improvements.
"""
import numpy as np
import time
import cv2
from scipy import ndimage as ndi
import sys
import os
# Add the project root to Python path
project_root = os.path.dirname(os.path.abspath(__file__))
sys.path.append(project_root)
# Import our optimized functions
from examples.instance_segmentation_example import (
create_instance_mask,
ensure_connected_instance_labels,
_vectorized_size_filter,
colorize_instance_mask
)
def create_test_images():
"""Create test images with different characteristics for benchmarking."""
# Sparse image (1% foreground)
sparse_img = np.zeros((512, 512), dtype=np.uint8)
for i in range(5):
center = (np.random.randint(50, 462), np.random.randint(50, 462))
cv2.circle(sparse_img, center, np.random.randint(10, 20), 1, -1)
# Medium density image (15% foreground)
medium_img = np.zeros((512, 512), dtype=np.uint8)
for i in range(25):
center = (np.random.randint(30, 482), np.random.randint(30, 482))
cv2.circle(medium_img, center, np.random.randint(8, 15), 1, -1)
# Dense image (40% foreground)
dense_img = np.zeros((512, 512), dtype=np.uint8)
for i in range(100):
center = (np.random.randint(20, 492), np.random.randint(20, 492))
cv2.circle(dense_img, center, np.random.randint(5, 12), 1, -1)
return {
'sparse': sparse_img,
'medium': medium_img,
'dense': dense_img
}
def benchmark_function(func, *args, **kwargs):
"""Benchmark a function call and return timing."""
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
return result, end_time - start_time
def test_create_instance_mask():
"""Test the optimized create_instance_mask function."""
print("π¬ Testing create_instance_mask() optimization...")
test_images = create_test_images()
for img_type, binary_mask in test_images.items():
print(f"\n {img_type.capitalize()} image ({np.sum(binary_mask)/binary_mask.size*100:.1f}% foreground):")
# Test with our optimized version
result, elapsed = benchmark_function(create_instance_mask, binary_mask)
num_objects = len(np.unique(result)) - 1
print(f" β
Optimized: {elapsed:.4f}s β {num_objects} objects")
def test_connectivity_check():
"""Test the ultra-fast connectivity checking."""
print("\nπ Testing ensure_connected_instance_labels() optimization...")
# Create a test mask with many labels (simulates real segmentation output)
test_mask = np.zeros((256, 256), dtype=np.int32)
label = 1
for i in range(0, 256, 20):
for j in range(0, 256, 20):
cv2.circle(test_mask, (j+10, i+10), 8, label, -1)
label += 1
num_labels = len(np.unique(test_mask)) - 1
density = np.sum(test_mask > 0) / test_mask.size
print(f" Test mask: {num_labels} labels, density {density:.4f}")
result, elapsed = benchmark_function(ensure_connected_instance_labels, test_mask)
print(f" β
Ultra-fast connectivity: {elapsed:.6f}s (likely skipped due to density heuristic)")
def test_size_filtering():
"""Test the vectorized size filtering."""
print("\nπ Testing _vectorized_size_filter() optimization...")
# Create a mask with objects of various sizes
test_mask = np.zeros((256, 256), dtype=np.int32)
label = 1
# Small objects (should be removed)
for i in range(5):
cv2.circle(test_mask, (50 + i*20, 50), 2, label, -1)
label += 1
# Medium objects (should be kept)
for i in range(5):
cv2.circle(test_mask, (50 + i*20, 100), 8, label, -1)
label += 1
# Large objects (should be removed if max_size set)
for i in range(3):
cv2.circle(test_mask, (80 + i*40, 150), 25, label, -1)
label += 1
original_count = len(np.unique(test_mask)) - 1
print(f" Original: {original_count} objects")
# Test size filtering
result, elapsed = benchmark_function(_vectorized_size_filter, test_mask, 20, 500)
filtered_count = len(np.unique(result)) - 1
print(f" β
Vectorized filtering: {elapsed:.6f}s β {filtered_count} objects (removed {original_count - filtered_count})")
def test_colorization():
"""Test the optimized colorization."""
print("\nπ¨ Testing colorize_instance_mask() optimization...")
# Test with different numbers of labels
test_cases = [
("Few labels", 5),
("Many labels", 100)
]
for case_name, num_labels in test_cases:
# Create test mask
test_mask = np.zeros((256, 256), dtype=np.int32)
for i in range(num_labels):
x = (i % 10) * 25 + 10
y = (i // 10) * 25 + 10
cv2.circle(test_mask, (x, y), 8, i + 1, -1)
result, elapsed = benchmark_function(colorize_instance_mask, test_mask)
print(f" {case_name} ({num_labels}): {elapsed:.6f}s")
def main():
"""Run all optimization tests."""
print("π SEGMENTATION OPTIMIZATION BENCHMARK")
print("=" * 50)
# Set random seed for reproducible results
np.random.seed(42)
# Run tests
test_create_instance_mask()
test_connectivity_check()
test_size_filtering()
test_colorization()
print("\n" + "=" * 50)
print("β
All optimization tests completed!")
print("\nπ‘ Key optimizations:")
print(" β’ Adaptive algorithm selection based on image characteristics")
print(" β’ Density-based early exits for connectivity checking")
print(" β’ Vectorized operations for size filtering")
print(" β’ Efficient color palettes and I/O operations")
print("\nπ― For maximum speed, use: --fast-mode")
if __name__ == "__main__":
main()