FaceNet PyTorch
facenet-pytorch provides pretrained PyTorch models for face detection (MTCNN) and facial recognition (InceptionResnetV1). It simplifies the process of integrating robust face analysis capabilities into Python applications, offering an easy-to-use API for tasks like detecting faces, extracting facial embeddings, and preparing faces for classification. The library is actively maintained, with regular updates to support newer PyTorch versions and address community feedback.
Common errors
-
ModuleNotFoundError: No module named 'facenet_pytorch'
cause The `facenet-pytorch` package is not installed in the active Python environment or there's a typo in the import statement.fixEnsure the package is correctly installed: `pip install facenet-pytorch`. Verify your virtual environment is activated and the import path is `from facenet_pytorch import ...`. -
ERROR: Cannot install facenet-pytorch because these package versions have conflicting dependencies.
cause Dependency conflicts, most commonly with `torch` or `numpy` versions required by other installed packages.fixUse a fresh virtual environment. Install `torch` and `torchvision` first with specific compatible versions (e.g., `pip install torch==2.2.0 torchvision==0.17.0`), then install `facenet-pytorch`. Consult `facenet-pytorch`'s PyPI page or GitHub for exact dependency ranges for your version. -
RuntimeError: No faces detected or image is empty
cause The `MTCNN` model failed to detect any faces in the provided image, or the image itself was not valid/empty.fixVerify the input image contains detectable faces and is properly loaded. Check `MTCNN` parameters like `min_face_size`, `thresholds`, and `image_size` if faces are very small or unusual. Inspect the image processing pipeline to ensure the image is not empty or corrupted. Handle `None` return from `mtcnn()` gracefully.
Warnings
- breaking Version 2.6.0 of `facenet-pytorch` requires specific PyTorch (`torch`) and torchvision versions. Installing with incompatible versions can lead to `pip` dependency resolution errors or runtime issues.
- gotcha Older versions of `facenet-pytorch` (prior to v2.5.3) could throw an `MTCNN module error` when no face was found in an image, leading to unexpected crashes.
- gotcha The library's `MTCNN` and `InceptionResnetV1` models expect `PIL.Image` objects as input. Passing other image formats (e.g., NumPy arrays without conversion) can lead to errors.
- deprecated `numpy` is throwing deprecation warnings for creating `ndarray` from nested sequences due to `facenet-pytorch`'s internal usage. This doesn't break functionality but indicates future incompatibility.
Install
-
pip install facenet-pytorch
Imports
- MTCNN
import facenet_pytorch.MTCNN
from facenet_pytorch import MTCNN
- InceptionResnetV1
import facenet_pytorch.InceptionResnetV1
from facenet_pytorch import InceptionResnetV1
Quickstart
import torch
from facenet_pytorch import MTCNN, InceptionResnetV1
from PIL import Image
import os
# Set device for GPU if available, else CPU
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print(f'Running on device: {device}')
# Initialize MTCNN for face detection
mtcnn = MTCNN(
image_size=160,
margin=0,
min_face_size=20,
thresholds=[0.6, 0.7, 0.7],
factor=0.709,
post_process=True,
device=device
)
# Initialize InceptionResnetV1 for face recognition
resnet = InceptionResnetV1(pretrained='vggface2').eval().to(device)
# Create a dummy image for demonstration (replace with your image path)
# In a real scenario, load an image from disk or URL
# Example: img = Image.open('path/to/your/image.jpg').convert('RGB')
# For a runnable example, we create a blank image
try:
# Attempt to load a real image for better demo, if it exists
dummy_image_path = os.path.join(os.path.dirname(__file__), 'dummy_face.jpg')
if os.path.exists(dummy_image_path):
img = Image.open(dummy_image_path).convert('RGB')
else:
# Create a blank image if no dummy_face.jpg is found
img = Image.new('RGB', (250, 250), color = 'red')
print("No 'dummy_face.jpg' found. Using a blank red image. Face detection will likely fail.")
except Exception as e:
img = Image.new('RGB', (250, 250), color = 'red')
print(f"Could not load image, creating a blank red image. Error: {e}")
# Detect faces
img_cropped = mtcnn(img)
if img_cropped is not None:
# Calculate face embedding
img_embedding = resnet(img_cropped.unsqueeze(0)).detach().cpu()
print("Face detected and embedding calculated.")
print(f"Embedding shape: {img_embedding.shape}")
else:
print("No face detected.")