A comprehensive 2D and 3D face analysis toolkit with state-of-the-art algorithms for face recognition, detection, and alignment.
—
Utilities for loading sample images and objects for testing, development, and examples. Provides convenient access to pre-packaged test data without requiring external files.
Load pre-packaged sample images for testing face analysis functionality.
def get_image(name, to_rgb=False) -> np.ndarray:
"""
Load sample image by name.
Parameters:
- name: str, sample image name (e.g., 'Tom_Hanks_54745', 'antelope')
- to_rgb: bool, convert from BGR to RGB format
Returns:
np.ndarray: loaded image array
"""Load pre-packaged sample objects and data structures for testing.
def get_object(name) -> Any:
"""
Load sample object by name.
Parameters:
- name: str, sample object name
Returns:
Any: loaded object (could be landmarks, parameters, etc.)
"""from insightface.data import get_image
import cv2
# Load sample image (BGR format by default)
img_bgr = get_image('antelope')
print(f"Image shape: {img_bgr.shape}")
# Load sample image in RGB format
img_rgb = get_image('antelope', to_rgb=True)
# Display sample image
cv2.imshow('Sample Image', img_bgr)
cv2.waitKey(0)
cv2.destroyAllWindows()from insightface.app import FaceAnalysis
from insightface.data import get_image
# Initialize face analysis
app = FaceAnalysis()
app.prepare(ctx_id=0)
# Test with sample image
sample_img = get_image('Tom_Hanks_54745')
faces = app.get(sample_img)
print(f"Detected {len(faces)} faces in sample image")
for i, face in enumerate(faces):
print(f"Face {i+1}: Age={face.age}, Gender={face.sex}")from insightface.data import get_object
# Load sample facial landmarks or parameters
sample_landmarks = get_object('sample_landmarks')
print(f"Sample landmarks shape: {sample_landmarks.shape}")
# Use in face processing
from insightface.utils.face_align import norm_crop
# Apply alignment using sample landmarks
aligned_face = norm_crop(sample_img, sample_landmarks, image_size=112)Common sample images and objects available through the data module:
'antelope' - Test image with clear face for detection/recognition testing'Tom_Hanks_54745' - Celebrity sample for recognition testing'sample_face' - Generic face sample for development'sample_landmarks' - Example facial landmark coordinates'sample_params' - Example 3D face parameters'test_embedding' - Sample face embedding vectordef test_face_pipeline():
"""Test complete face analysis pipeline with sample data."""
from insightface.app import FaceAnalysis
from insightface.data import get_image
# Load components
app = FaceAnalysis()
app.prepare(ctx_id=0)
# Test with multiple sample images
test_images = ['antelope', 'Tom_Hanks_54745']
for img_name in test_images:
print(f"\nTesting with {img_name}:")
# Load sample image
img = get_image(img_name)
# Analyze faces
faces = app.get(img)
if faces:
face = faces[0] # First detected face
print(f" Detection confidence: {face.det_score:.3f}")
print(f" Age: {face.age}, Gender: {face.sex}")
print(f" Embedding shape: {face.embedding.shape}")
else:
print(f" No faces detected in {img_name}")
# Run development test
test_face_pipeline()def create_custom_sample():
"""Example of creating custom sample data for your application."""
import pickle
import os
# Create custom landmarks for your specific use case
custom_landmarks = np.array([
[38.2946, 51.6963], # Left eye
[73.5318, 51.5014], # Right eye
[56.0252, 71.7366], # Nose
[41.5493, 92.3655], # Left mouth
[70.7299, 92.2041] # Right mouth
])
# Save as sample object
sample_dir = os.path.expanduser('~/.insightface/objects')
os.makedirs(sample_dir, exist_ok=True)
with open(os.path.join(sample_dir, 'my_landmarks.pkl'), 'wb') as f:
pickle.dump(custom_landmarks, f)
print("Custom sample data created")
# Create and use custom sample
create_custom_sample()
custom_landmarks = get_object('my_landmarks')import unittest
from insightface.data import get_image, get_object
from insightface.app import FaceAnalysis
class TestFaceAnalysis(unittest.TestCase):
def setUp(self):
"""Set up test fixtures with sample data."""
self.app = FaceAnalysis()
self.app.prepare(ctx_id=0)
self.sample_img = get_image('antelope')
def test_face_detection(self):
"""Test face detection with sample image."""
faces = self.app.get(self.sample_img)
self.assertGreater(len(faces), 0, "Should detect at least one face")
def test_face_attributes(self):
"""Test face attribute prediction."""
faces = self.app.get(self.sample_img)
if faces:
face = faces[0]
self.assertIsNotNone(face.age, "Age should be predicted")
self.assertIsNotNone(face.gender, "Gender should be predicted")
def test_face_embedding(self):
"""Test face embedding extraction."""
faces = self.app.get(self.sample_img)
if faces:
face = faces[0]
self.assertIsNotNone(face.embedding, "Embedding should be extracted")
self.assertEqual(face.embedding.shape[0], 512, "Embedding should be 512-dimensional")
if __name__ == '__main__':
unittest.main()Install with Tessl CLI
npx tessl i tessl/pypi-insightface