{"id":8984,"library":"facenet-pytorch","title":"FaceNet PyTorch","description":"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.","status":"active","version":"2.6.0","language":"en","source_language":"en","source_url":"https://github.com/timesler/facenet-pytorch","tags":["face-detection","face-recognition","pytorch","deep-learning","computer-vision","ai-ml"],"install":[{"cmd":"pip install facenet-pytorch","lang":"bash","label":"Install stable release"}],"dependencies":[{"reason":"Core numerical operations.","package":"numpy","optional":false},{"reason":"Image manipulation (e.g., loading, saving, processing images for models).","package":"Pillow","optional":false},{"reason":"Used for downloading pretrained model weights.","package":"requests","optional":false},{"reason":"Underlying deep learning framework. Requires version <2.3.0,>=2.2.0 for facenet-pytorch 2.6.0.","package":"torch","optional":false},{"reason":"Provides datasets, models, and image transformations for PyTorch. Requires version <0.18.0,>=0.17.0.","package":"torchvision","optional":false},{"reason":"Progress bars for model loading and processing.","package":"tqdm","optional":false}],"imports":[{"note":"MTCNN is a class within the facenet_pytorch package, not a top-level module.","wrong":"import facenet_pytorch.MTCNN","symbol":"MTCNN","correct":"from facenet_pytorch import MTCNN"},{"note":"InceptionResnetV1 is a class within the facenet_pytorch package, not a top-level module.","wrong":"import facenet_pytorch.InceptionResnetV1","symbol":"InceptionResnetV1","correct":"from facenet_pytorch import InceptionResnetV1"}],"quickstart":{"code":"import torch\nfrom facenet_pytorch import MTCNN, InceptionResnetV1\nfrom PIL import Image\nimport os\n\n# Set device for GPU if available, else CPU\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\nprint(f'Running on device: {device}')\n\n# Initialize MTCNN for face detection\nmtcnn = MTCNN(\n    image_size=160,\n    margin=0,\n    min_face_size=20,\n    thresholds=[0.6, 0.7, 0.7],\n    factor=0.709,\n    post_process=True,\n    device=device\n)\n\n# Initialize InceptionResnetV1 for face recognition\nresnet = InceptionResnetV1(pretrained='vggface2').eval().to(device)\n\n# Create a dummy image for demonstration (replace with your image path)\n# In a real scenario, load an image from disk or URL\n# Example: img = Image.open('path/to/your/image.jpg').convert('RGB')\n\n# For a runnable example, we create a blank image\ntry:\n    # Attempt to load a real image for better demo, if it exists\n    dummy_image_path = os.path.join(os.path.dirname(__file__), 'dummy_face.jpg')\n    if os.path.exists(dummy_image_path):\n        img = Image.open(dummy_image_path).convert('RGB')\n    else:\n        # Create a blank image if no dummy_face.jpg is found\n        img = Image.new('RGB', (250, 250), color = 'red')\n        print(\"No 'dummy_face.jpg' found. Using a blank red image. Face detection will likely fail.\")\nexcept Exception as e:\n    img = Image.new('RGB', (250, 250), color = 'red')\n    print(f\"Could not load image, creating a blank red image. Error: {e}\")\n\n# Detect faces\nimg_cropped = mtcnn(img)\n\nif img_cropped is not None:\n    # Calculate face embedding\n    img_embedding = resnet(img_cropped.unsqueeze(0)).detach().cpu()\n    print(\"Face detected and embedding calculated.\")\n    print(f\"Embedding shape: {img_embedding.shape}\")\nelse:\n    print(\"No face detected.\")","lang":"python","description":"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."},"warnings":[{"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`.","message":"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.","severity":"breaking","affected_versions":"2.6.0+"},{"fix":"Upgrade to `facenet-pytorch` version 2.5.3 or newer, where this issue was addressed.","message":"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.","severity":"gotcha","affected_versions":"<2.5.3"},{"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)`.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"`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.","severity":"deprecated","affected_versions":"2.5.3+"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"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 ...`.","cause":"The `facenet-pytorch` package is not installed in the active Python environment or there's a typo in the import statement.","error":"ModuleNotFoundError: No module named 'facenet_pytorch'"},{"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.","cause":"Dependency conflicts, most commonly with `torch` or `numpy` versions required by other installed packages.","error":"ERROR: Cannot install facenet-pytorch because these package versions have conflicting dependencies."},{"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.","cause":"The `MTCNN` model failed to detect any faces in the provided image, or the image itself was not valid/empty.","error":"RuntimeError: No faces detected or image is empty"}]}