Registry / ai-ml / facenet-pytorch

facenet-pytorch

JSON →
library2.6.0pypypi✓ verified 86d ago

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.

pip install facenet-pytorch
INSTALL
IMPORT
SIG · FACENET-PYTORCH
F
facenet-pytorch
ai-mlpythonv2.6.0
Install
81.5s avg
Import
8191ms
Disk
2532MB
Pass rate
8/ 10
Env Coverage8 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.2.9 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
glibc
py 3.10
✓ —
✓ 82.25s
py 3.11
✓ —
✓ 79.6s
py 3.12
✓ —
✓ 66.25s
py 3.13
✕ build_error
✕ build_error
py 3.9
✓ —
✓ 97.75s
2532MB installed
● package 2532MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

MTCNN
from facenet_pytorch import MTCNN
import facenet_pytorch.MTCNN
MTCNN is a class within the facenet_pytorch package, not a top-level module.
InceptionResnetV1
from facenet_pytorch import InceptionResnetV1
import facenet_pytorch.InceptionResnetV1
InceptionResnetV1 is a class within the facenet_pytorch package, not a top-level module.

This quickstart demonstrates how to use `facenet-pytorch` to detect a face in an image using `MTCNN` and then compute its 512-dimensional embedding using `InceptionResnetV1`. It sets up a PyTorch device (GPU if available, otherwise CPU) and initializes both models. It includes a placeholder for image loading and handles cases where no face is detected.

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.")
Debug
Known issues
breakingVersion 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.
fix
Ensure your `torch` version is between 2.2.0 and 2.3.0 (`<2.3.0,>=2.2.0`) and `torchvision` is between 0.17.0 and 0.18.0 (`<0.18.0,>=0.17.0`). Consider using a virtual environment and installing `torch` and `torchvision` first, then `facenet-pytorch`.
affects: 2.6.0+
gotchaOlder 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.
fix
Upgrade to `facenet-pytorch` version 2.5.3 or newer, where this issue was addressed.
affects: <2.5.3
gotchaThe 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.
fix
Always convert your image data to a `PIL.Image` object before passing it to `MTCNN` or `InceptionResnetV1`. E.g., `Image.fromarray(numpy_array)` or `Image.open(image_path)`.
affects: All versions
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.
fix
While this is often an upstream issue in `facenet-pytorch` itself or its dependencies, users should keep their `numpy` version updated and monitor for future releases that address this warning.
affects: 2.5.3+
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'facenet_pytorch'
The `facenet-pytorch` package is not installed in the active Python environment or there's a typo in the import statement.
fix
Ensure 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.
Dependency conflicts, most commonly with `torch` or `numpy` versions required by other installed packages.
fix
Use 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
The `MTCNN` model failed to detect any faces in the provided image, or the image itself was not valid/empty.
fix
Verify 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.
Upgrade
Version history
2.6.0latest on PyPI · released Apr 29, 2024
Audit
Dependencies
numpyrequiredCore numerical operations.
PillowrequiredImage manipulation (e.g., loading, saving, processing images for models).
requestsrequiredUsed for downloading pretrained model weights.
torchrequiredUnderlying deep learning framework. Requires version <2.3.0,>=2.2.0 for facenet-pytorch 2.6.0.
torchvisionrequiredProvides datasets, models, and image transformations for PyTorch. Requires version <0.18.0,>=0.17.0.
tqdmrequiredProgress bars for model loading and processing.
Agent activity
40 hits · last 30 days
node
38
OpenAI (training)
1
Resources
facenet-pytorch — pip install facenet-pytorch · libregistry