RetinaFace Deep Face Detection
RetinaFace is a deep learning-based, cutting-edge facial detector for Python, providing high-precision face localization and facial landmarks. It's built on a TensorFlow re-implementation of the original RetinaFace model from the InsightFace project. The library simplifies the underlying C dependencies and handles pre-trained weight downloads automatically, making it pip-compatible and easy to use. The current version is 0.0.17, with a moderately active release cadence addressing compatibility and performance improvements.
Common errors
-
ModuleNotFoundError: No module named 'retinaface'
cause The `retina-face` package is not installed or installed in a different Python environment.fixEnsure the package is installed in your active environment: `pip install retina-face`. -
tensorflow.python.framework.errors_impl.InvalidArgumentError: Invalid padding value 'VALID'. Must be 'SAME' or 'VALID'.
cause An older version of TensorFlow is being used with a `retina-face` version (e.g., v0.0.15) that expected a lowercase 'valid' for padding due to a TensorFlow API change. [cite: v0.0.15 release]fixUpgrade `retina-face` to the latest version (`pip install --upgrade retina-face`) or ensure your TensorFlow version is compatible (e.g., TensorFlow 2.16+ with RetinaFace 0.0.16+). -
ValueError: Path not found: [image_path]
cause The image file specified in `RetinaFace.detect_faces()` does not exist at the given path.fixVerify the image file path is correct and the file exists. Use an absolute path or ensure the image is in the current working directory. -
AttributeError: 'NoneType' object has no attribute 'shape' (often when reading image with OpenCV)
cause OpenCV (cv2.imread) failed to load the image, returning `None`. This can happen if the image path is incorrect, the image is corrupted, or required image codecs are missing.fixCheck the image path. Ensure `opencv-python` (or `opencv-python-headless`) is correctly installed and that the image file is valid and readable.
Warnings
- breaking TensorFlow versions 2.16 and later require RetinaFace v0.0.16 or higher for full compatibility. Older versions might encounter issues due to TensorFlow API changes. [cite: v0.0.16 release]
- breaking In `retina-face` v0.0.15, TensorFlow's padding argument changed from 'VALID' to 'valid' (lowercase), causing exceptions in older TensorFlow versions if 'VALID' was used. The library was updated to use 'valid'. [cite: v0.0.15 release]
- gotcha From v0.0.15 onwards, the internal processing order was changed to align faces first, then detect, which can lead to different (often improved) results, especially by reducing 'meaningless black pixels'. [cite: v0.0.15 release]
- gotcha Version 0.0.17 introduced validation for projected coordinates against the base image size to prevent failures from invalid coordinates. While a fix, it might expose underlying issues with input images or detection in extreme cases that were previously silently handled. [cite: v0.0.17 release]
Install
-
pip install retina-face -
conda install -c conda-forge retina-face
Imports
- RetinaFace
from retinaface import RetinaFace
Quickstart
import cv2
import os
from retinaface import RetinaFace
# Create a dummy image for demonstration if it doesn't exist
image_path = "test_image.jpg"
if not os.path.exists(image_path):
# Create a blank white image
dummy_image = 255 * (1 + 0 * range(100)).reshape(100, 100, 1) # White image
dummy_image = cv2.cvtColor(dummy_image, cv2.COLOR_GRAY2BGR)
cv2.imwrite(image_path, dummy_image)
print(f"Created a dummy image at {image_path}")
try:
# Detect faces in an image
# The detect_faces function can accept an image path or a NumPy array.
faces = RetinaFace.detect_faces(image_path)
if isinstance(faces, dict):
for face_name, face_data in faces.items():
print(f"--- {face_name} ---")
print(f" Score: {face_data['score']}")
print(f" Facial Area: {face_data['facial_area']}")
print(f" Landmarks: {face_data['landmarks']}")
elif faces is None:
print(f"No faces detected in {image_path}")
else:
print("Unexpected output format from RetinaFace.detect_faces")
# Optional: Draw detections on the image and display (requires opencv-python-headless or opencv-python)
# img = cv2.imread(image_path)
# if img is not None:
# result_img = RetinaFace.draw_landmarks(img, faces)
# cv2.imshow("Detected Faces", result_img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
except Exception as e:
print(f"An error occurred: {e}")