0
# Sample Data and Objects
1
2
Utilities for loading sample images and objects for testing, development, and examples. Provides convenient access to pre-packaged test data without requiring external files.
3
4
## Capabilities
5
6
### Sample Image Loading
7
8
Load pre-packaged sample images for testing face analysis functionality.
9
10
```python { .api }
11
def get_image(name, to_rgb=False) -> np.ndarray:
12
"""
13
Load sample image by name.
14
15
Parameters:
16
- name: str, sample image name (e.g., 'Tom_Hanks_54745', 'antelope')
17
- to_rgb: bool, convert from BGR to RGB format
18
19
Returns:
20
np.ndarray: loaded image array
21
"""
22
```
23
24
### Sample Object Loading
25
26
Load pre-packaged sample objects and data structures for testing.
27
28
```python { .api }
29
def get_object(name) -> Any:
30
"""
31
Load sample object by name.
32
33
Parameters:
34
- name: str, sample object name
35
36
Returns:
37
Any: loaded object (could be landmarks, parameters, etc.)
38
"""
39
```
40
41
## Usage Examples
42
43
### Loading Sample Images
44
45
```python
46
from insightface.data import get_image
47
import cv2
48
49
# Load sample image (BGR format by default)
50
img_bgr = get_image('antelope')
51
print(f"Image shape: {img_bgr.shape}")
52
53
# Load sample image in RGB format
54
img_rgb = get_image('antelope', to_rgb=True)
55
56
# Display sample image
57
cv2.imshow('Sample Image', img_bgr)
58
cv2.waitKey(0)
59
cv2.destroyAllWindows()
60
```
61
62
### Testing Face Analysis with Sample Data
63
64
```python
65
from insightface.app import FaceAnalysis
66
from insightface.data import get_image
67
68
# Initialize face analysis
69
app = FaceAnalysis()
70
app.prepare(ctx_id=0)
71
72
# Test with sample image
73
sample_img = get_image('Tom_Hanks_54745')
74
faces = app.get(sample_img)
75
76
print(f"Detected {len(faces)} faces in sample image")
77
for i, face in enumerate(faces):
78
print(f"Face {i+1}: Age={face.age}, Gender={face.sex}")
79
```
80
81
### Loading Sample Objects
82
83
```python
84
from insightface.data import get_object
85
86
# Load sample facial landmarks or parameters
87
sample_landmarks = get_object('sample_landmarks')
88
print(f"Sample landmarks shape: {sample_landmarks.shape}")
89
90
# Use in face processing
91
from insightface.utils.face_align import norm_crop
92
93
# Apply alignment using sample landmarks
94
aligned_face = norm_crop(sample_img, sample_landmarks, image_size=112)
95
```
96
97
### Available Sample Data
98
99
Common sample images and objects available through the data module:
100
101
#### Sample Images:
102
- `'antelope'` - Test image with clear face for detection/recognition testing
103
- `'Tom_Hanks_54745'` - Celebrity sample for recognition testing
104
- `'sample_face'` - Generic face sample for development
105
106
#### Sample Objects:
107
- `'sample_landmarks'` - Example facial landmark coordinates
108
- `'sample_params'` - Example 3D face parameters
109
- `'test_embedding'` - Sample face embedding vector
110
111
### Development and Testing Workflow
112
113
```python
114
def test_face_pipeline():
115
"""Test complete face analysis pipeline with sample data."""
116
from insightface.app import FaceAnalysis
117
from insightface.data import get_image
118
119
# Load components
120
app = FaceAnalysis()
121
app.prepare(ctx_id=0)
122
123
# Test with multiple sample images
124
test_images = ['antelope', 'Tom_Hanks_54745']
125
126
for img_name in test_images:
127
print(f"\nTesting with {img_name}:")
128
129
# Load sample image
130
img = get_image(img_name)
131
132
# Analyze faces
133
faces = app.get(img)
134
135
if faces:
136
face = faces[0] # First detected face
137
print(f" Detection confidence: {face.det_score:.3f}")
138
print(f" Age: {face.age}, Gender: {face.sex}")
139
print(f" Embedding shape: {face.embedding.shape}")
140
else:
141
print(f" No faces detected in {img_name}")
142
143
# Run development test
144
test_face_pipeline()
145
```
146
147
### Creating Custom Sample Data
148
149
```python
150
def create_custom_sample():
151
"""Example of creating custom sample data for your application."""
152
import pickle
153
import os
154
155
# Create custom landmarks for your specific use case
156
custom_landmarks = np.array([
157
[38.2946, 51.6963], # Left eye
158
[73.5318, 51.5014], # Right eye
159
[56.0252, 71.7366], # Nose
160
[41.5493, 92.3655], # Left mouth
161
[70.7299, 92.2041] # Right mouth
162
])
163
164
# Save as sample object
165
sample_dir = os.path.expanduser('~/.insightface/objects')
166
os.makedirs(sample_dir, exist_ok=True)
167
168
with open(os.path.join(sample_dir, 'my_landmarks.pkl'), 'wb') as f:
169
pickle.dump(custom_landmarks, f)
170
171
print("Custom sample data created")
172
173
# Create and use custom sample
174
create_custom_sample()
175
custom_landmarks = get_object('my_landmarks')
176
```
177
178
### Integration with Testing Frameworks
179
180
```python
181
import unittest
182
from insightface.data import get_image, get_object
183
from insightface.app import FaceAnalysis
184
185
class TestFaceAnalysis(unittest.TestCase):
186
def setUp(self):
187
"""Set up test fixtures with sample data."""
188
self.app = FaceAnalysis()
189
self.app.prepare(ctx_id=0)
190
self.sample_img = get_image('antelope')
191
192
def test_face_detection(self):
193
"""Test face detection with sample image."""
194
faces = self.app.get(self.sample_img)
195
self.assertGreater(len(faces), 0, "Should detect at least one face")
196
197
def test_face_attributes(self):
198
"""Test face attribute prediction."""
199
faces = self.app.get(self.sample_img)
200
if faces:
201
face = faces[0]
202
self.assertIsNotNone(face.age, "Age should be predicted")
203
self.assertIsNotNone(face.gender, "Gender should be predicted")
204
205
def test_face_embedding(self):
206
"""Test face embedding extraction."""
207
faces = self.app.get(self.sample_img)
208
if faces:
209
face = faces[0]
210
self.assertIsNotNone(face.embedding, "Embedding should be extracted")
211
self.assertEqual(face.embedding.shape[0], 512, "Embedding should be 512-dimensional")
212
213
if __name__ == '__main__':
214
unittest.main()
215
```