Skip to content

UniFace: A Unified Face Analysis Library for Python | Detection, alignment, landmarks, face-mesh, recognition, parsing, gaze, attributes and anti-spoofing under one API.

feat: Update API format and gaze estimation models (#82)

Yakhyokhuja Valikhujaev971775b2e810
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 1edfa91..94e3bde 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -82,23 +82,23 @@ def process(items: List[str], config: Optional[Dict[str, int]] = None) -> Tuple[
Use [Google-style docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings) for all public APIs:
```python
-def detect_faces(image: np.ndarray, threshold: float = 0.5) -> list[Face]:
- """Detect faces in an image.
+def create_detector(method: str = 'retinaface', **kwargs: Any) -> BaseDetector:
+ """Factory function to create face detectors.
Args:
- image: Input image as a numpy array with shape (H, W, C) in BGR format.
- threshold: Confidence threshold for filtering detections. Defaults to 0.5.
+ method: Detection method. Options: 'retinaface', 'scrfd', 'yolov5face', 'yolov8face'.
+ **kwargs: Detector-specific parameters.
Returns:
- List of Face objects containing bounding boxes, confidence scores,
- and facial landmarks.
+ Initialized detector instance.
Raises:
- ValueError: If the input image has invalid dimensions.
+ ValueError: If method is not supported.
Example:
- >>> from uniface import detect_faces
- >>> faces = detect_faces(image, threshold=0.8)
+ >>> from uniface import create_detector
+ >>> detector = create_detector('retinaface', confidence_threshold=0.8)
+ >>> faces = detector.detect(image)
>>> print(f"Found {len(faces)} faces")
"""
```
@@ -174,16 +174,16 @@ When adding a new model or feature:
Example notebooks demonstrating library usage:
-| Example | Notebook |
-|---------|----------|
-| Face Detection | [01_face_detection.ipynb](examples/01_face_detection.ipynb) |
-| Face Alignment | [02_face_alignment.ipynb](examples/02_face_alignment.ipynb) |
-| Face Verification | [03_face_verification.ipynb](examples/03_face_verification.ipynb) |
-| Face Search | [04_face_search.ipynb](examples/04_face_search.ipynb) |
-| Face Analyzer | [05_face_analyzer.ipynb](examples/05_face_analyzer.ipynb) |
-| Face Parsing | [06_face_parsing.ipynb](examples/06_face_parsing.ipynb) |
+| Example | Notebook |
+| ------------------ | ------------------------------------------------------------------- |
+| Face Detection | [01_face_detection.ipynb](examples/01_face_detection.ipynb) |
+| Face Alignment | [02_face_alignment.ipynb](examples/02_face_alignment.ipynb) |
+| Face Verification | [03_face_verification.ipynb](examples/03_face_verification.ipynb) |
+| Face Search | [04_face_search.ipynb](examples/04_face_search.ipynb) |
+| Face Analyzer | [05_face_analyzer.ipynb](examples/05_face_analyzer.ipynb) |
+| Face Parsing | [06_face_parsing.ipynb](examples/06_face_parsing.ipynb) |
| Face Anonymization | [07_face_anonymization.ipynb](examples/07_face_anonymization.ipynb) |
-| Gaze Estimation | [08_gaze_estimation.ipynb](examples/08_gaze_estimation.ipynb) |
+| Gaze Estimation | [08_gaze_estimation.ipynb](examples/08_gaze_estimation.ipynb) |
## Questions?
diff --git a/docs/models.md b/docs/models.md
index 6f3271c..9184874 100644
--- a/docs/models.md
+++ b/docs/models.md
@@ -22,7 +22,7 @@ RetinaFace models are trained on the WIDER FACE dataset.
!!! info "Accuracy & Benchmarks"
**Accuracy**: WIDER FACE validation set (Easy/Medium/Hard subsets) - from [RetinaFace paper](https://arxiv.org/abs/1905.00641)
- **Speed**: Benchmark on your own hardware using `python tools/detection.py --source <image>`
+ **Speed**: Benchmark on your own hardware using `python tools/detect.py --source <image>`
---
@@ -38,7 +38,7 @@ SCRFD (Sample and Computation Redistribution for Efficient Face Detection) model
!!! info "Accuracy & Benchmarks"
**Accuracy**: WIDER FACE validation set - from [SCRFD paper](https://arxiv.org/abs/2105.04714)
- **Speed**: Benchmark on your own hardware using `python tools/detection.py --source <image>`
+ **Speed**: Benchmark on your own hardware using `python tools/detect.py --source <image>`
---
@@ -55,7 +55,7 @@ YOLOv5-Face models provide detection with 5-point facial landmarks, trained on W
!!! info "Accuracy & Benchmarks"
**Accuracy**: WIDER FACE validation set - from [YOLOv5-Face paper](https://arxiv.org/abs/2105.12931)
- **Speed**: Benchmark on your own hardware using `python tools/detection.py --source <image>`
+ **Speed**: Benchmark on your own hardware using `python tools/detect.py --source <image>`
!!! note "Fixed Input Size"
All YOLOv5-Face models use a fixed input size of 640×640.
@@ -74,7 +74,7 @@ YOLOv8-Face models use anchor-free design with DFL (Distribution Focal Loss) for
!!! info "Accuracy & Benchmarks"
**Accuracy**: WIDER FACE validation set (Easy/Medium/Hard subsets)
- **Speed**: Benchmark on your own hardware using `python tools/detection.py --source <image> --method yolov8face`
+ **Speed**: Benchmark on your own hardware using `python tools/detect.py --source <image> --method yolov8face`
!!! note "Fixed Input Size"
All YOLOv8-Face models use a fixed input size of 640×640.
@@ -219,7 +219,7 @@ Facial landmark localization model.
| `AFFECNET7` | 7 | 0.5M | 2MB |
| `AFFECNET8` | 8 | 0.5M | 2MB |
-**Classes (7)**: Neutral, Happy, Sad, Surprise, Fear, Disgust, Anger
+**Classes (7)**: Neutral, Happy, Sad, Surprise, Fear, Disgust, Angry
**Classes (8)**: Above + Contempt
@@ -279,13 +279,13 @@ BiSeNet (Bilateral Segmentation Network) models for semantic face parsing. Segme
| # | Class | # | Class | # | Class |
|---|-------|---|-------|---|-------|
-| 1 | Background | 8 | Left Ear | 15 | Neck |
-| 2 | Skin | 9 | Right Ear | 16 | Neck Lace |
-| 3 | Left Eyebrow | 10 | Ear Ring | 17 | Cloth |
-| 4 | Right Eyebrow | 11 | Nose | 18 | Hair |
-| 5 | Left Eye | 12 | Mouth | 19 | Hat |
-| 6 | Right Eye | 13 | Upper Lip | | |
-| 7 | Eye Glasses | 14 | Lower Lip | | |
+| 0 | Background | 7 | Left Ear | 14 | Neck |
+| 1 | Skin | 8 | Right Ear | 15 | Neck Lace |
+| 2 | Left Eyebrow | 9 | Ear Ring | 16 | Cloth |
+| 3 | Right Eyebrow | 10 | Nose | 17 | Hair |
+| 4 | Left Eye | 11 | Mouth | 18 | Hat |
+| 5 | Right Eye | 12 | Upper Lip | | |
+| 6 | Eye Glasses | 13 | Lower Lip | | |
**Applications:**
diff --git a/docs/modules/attributes.md b/docs/modules/attributes.md
index 872f87e..b35cdb9 100644
--- a/docs/modules/attributes.md
+++ b/docs/modules/attributes.md
@@ -127,7 +127,7 @@ from uniface.attribute import Emotion
from uniface.constants import DDAMFNWeights
detector = RetinaFace()
-emotion = Emotion(model_weights=DDAMFNWeights.AFFECNET7)
+emotion = Emotion(model_name=DDAMFNWeights.AFFECNET7)
faces = detector.detect(image)
@@ -149,7 +149,7 @@ for face in faces:
| Surprise |
| Fear |
| Disgust |
- | Anger |
+ | Angry |
=== "8-Class (AFFECNET8)"
@@ -161,7 +161,7 @@ for face in faces:
| Surprise |
| Fear |
| Disgust |
- | Anger |
+ | Angry |
| Contempt |
### Model Variants
@@ -171,10 +171,10 @@ from uniface.attribute import Emotion
from uniface.constants import DDAMFNWeights
# 7-class emotion
-emotion = Emotion(model_weights=DDAMFNWeights.AFFECNET7)
+emotion = Emotion(model_name=DDAMFNWeights.AFFECNET7)
# 8-class emotion
-emotion = Emotion(model_weights=DDAMFNWeights.AFFECNET8)
+emotion = Emotion(model_name=DDAMFNWeights.AFFECNET8)
```
---
diff --git a/docs/modules/detection.md b/docs/modules/detection.md
index 07cb0e6..b60fd4c 100644
--- a/docs/modules/detection.md
+++ b/docs/modules/detection.md
@@ -238,22 +238,6 @@ detector = create_detector('yolov8face')
---
-## High-Level API
-
-One-line detection:
-
-```python
-from uniface.detection import detect_faces
-
-# Using RetinaFace (default)
-faces = detect_faces(image, method='retinaface', confidence_threshold=0.5)
-
-# Using YOLOv8-Face
-faces = detect_faces(image, method='yolov8face', confidence_threshold=0.5)
-```
-
----
-
## Output Format
All detectors return `list[Face]`:
@@ -296,7 +280,7 @@ cv2.imwrite("result.jpg", image)
Benchmark on your hardware:
```bash
-python tools/detection.py --source image.jpg
+python tools/detect.py --source image.jpg
```
---
diff --git a/docs/modules/parsing.md b/docs/modules/parsing.md
index a45a3f2..50a0127 100644
--- a/docs/modules/parsing.md
+++ b/docs/modules/parsing.md
@@ -177,23 +177,19 @@ def apply_lip_color(image, mask, color=(180, 50, 50)):
"""Apply lip color using parsing mask."""
result = image.copy()
- # Get lip mask (upper + lower lip)
- lip_mask = ((mask == 13) | (mask == 14)).astype(np.uint8)
+ # Get lip mask (upper lip=12, lower lip=13)
+ lip_mask = ((mask == 12) | (mask == 13)).astype(np.uint8)
# Create color overlay
overlay = np.zeros_like(image)
overlay[:] = color
- # Blend with original
- lip_region = cv2.bitwise_and(overlay, overlay, mask=lip_mask)
- non_lip = cv2.bitwise_and(result, result, mask=1 - lip_mask)
-
- # Combine with alpha blending
+ # Alpha blend lip region
alpha = 0.4
- result = cv2.addWeighted(result, 1 - alpha * lip_mask[:,:,np.newaxis] / 255,
- lip_region, alpha, 0)
+ mask_3ch = lip_mask[:, :, np.newaxis]
+ result = np.where(mask_3ch, (image * (1 - alpha) + overlay * alpha).astype(np.uint8), result)
- return result.astype(np.uint8)
+ return result
```
### Background Replacement
@@ -268,7 +264,7 @@ faces = detector.detect(image)
for face in faces:
if face.landmarks is not None:
- mask = parser.parse(image, face.landmarks)
+ mask = parser.parse(image, landmarks=face.landmarks)
print(f"Mask shape: {mask.shape}") # (H, W), values in [0, 1]
```
@@ -296,7 +292,7 @@ parser = XSeg(
```python
# Full pipeline: align -> segment -> warp back to original space
-mask = parser.parse(image, landmarks)
+mask = parser.parse(image, landmarks=landmarks)
# For pre-aligned face crops
mask = parser.parse_aligned(face_crop)
diff --git a/docs/modules/privacy.md b/docs/modules/privacy.md
index ab87487..f70916a 100644
--- a/docs/modules/privacy.md
+++ b/docs/modules/privacy.md
@@ -18,23 +18,6 @@ Face anonymization protects privacy by blurring or obscuring faces in images and
## Quick Start
-### One-Line Anonymization
-
-```python
-from uniface.privacy import anonymize_faces
-import cv2
-
-image = cv2.imread("group_photo.jpg")
-anonymized = anonymize_faces(image, method='pixelate')
-cv2.imwrite("anonymized.jpg", anonymized)
-```
-
----
-
-## BlurFace Class
-
-For more control, use the `BlurFace` class:
-
```python
from uniface.detection import RetinaFace
from uniface.privacy import BlurFace
@@ -59,7 +42,7 @@ cv2.imwrite("anonymized.jpg", anonymized)
Blocky pixelation effect (common in news media):
```python
-blurrer = BlurFace(method='pixelate', pixel_blocks=10)
+blurrer = BlurFace(method='pixelate', pixel_blocks=15)
```
| Parameter | Default | Description |
@@ -259,13 +242,13 @@ for method in methods:
```bash
# Anonymize image with pixelation
-python tools/face_anonymize.py --source photo.jpg
+python tools/anonymize.py --source photo.jpg
# Real-time webcam
-python tools/face_anonymize.py --source 0 --method gaussian
+python tools/anonymize.py --source 0 --method gaussian
# Custom blur strength
-python tools/face_anonymize.py --source photo.jpg --method gaussian --blur-strength 5.0
+python tools/anonymize.py --source photo.jpg --method gaussian --blur-strength 5.0
```
---
diff --git a/docs/quickstart.md b/docs/quickstart.md
index 210f2b6..cb7522f 100644
--- a/docs/quickstart.md
+++ b/docs/quickstart.md
@@ -266,25 +266,23 @@ print(f"Detected {len(np.unique(mask))} facial components")
Blur faces for privacy protection:
```python
-from uniface.privacy import anonymize_faces
import cv2
+from uniface.detection import RetinaFace
+from uniface.privacy import BlurFace
+
+detector = RetinaFace()
+blurrer = BlurFace(method='pixelate')
-# One-liner: automatic detection and blurring
image = cv2.imread("group_photo.jpg")
-anonymized = anonymize_faces(image, method='pixelate')
+faces = detector.detect(image)
+anonymized = blurrer.anonymize(image, faces)
cv2.imwrite("anonymized.jpg", anonymized)
```
-**Manual control:**
+**Custom blur settings:**
```python
-from uniface.detection import RetinaFace
-from uniface.privacy import BlurFace
-
-detector = RetinaFace()
blurrer = BlurFace(method='gaussian', blur_strength=5.0)
-
-faces = detector.detect(image)
anonymized = blurrer.anonymize(image, faces)
```
diff --git a/docs/recipes/anonymize-stream.md b/docs/recipes/anonymize-stream.md
index 104de44..228d0f6 100644
--- a/docs/recipes/anonymize-stream.md
+++ b/docs/recipes/anonymize-stream.md
@@ -67,14 +67,19 @@ out.release()
---
-## One-Liner for Images
+## Single Image
```python
-from uniface.privacy import anonymize_faces
import cv2
+from uniface.detection import RetinaFace
+from uniface.privacy import BlurFace
+
+detector = RetinaFace()
+blurrer = BlurFace(method='pixelate')
image = cv2.imread("photo.jpg")
-result = anonymize_faces(image, method='pixelate')
+faces = detector.detect(image)
+result = blurrer.anonymize(image, faces)
cv2.imwrite("anonymized.jpg", result)
```
@@ -84,7 +89,7 @@ cv2.imwrite("anonymized.jpg", result)
| Method | Usage |
|--------|-------|
-| Pixelate | `BlurFace(method='pixelate', pixel_blocks=10)` |
+| Pixelate | `BlurFace(method='pixelate', pixel_blocks=15)` |
| Gaussian | `BlurFace(method='gaussian', blur_strength=3.0)` |
| Blackout | `BlurFace(method='blackout', color=(0,0,0))` |
| Elliptical | `BlurFace(method='elliptical', margin=20)` |
diff --git a/examples/07_face_anonymization.ipynb b/examples/07_face_anonymization.ipynb
index fe22b85..bb1b8c2 100644
--- a/examples/07_face_anonymization.ipynb
+++ b/examples/07_face_anonymization.ipynb
@@ -63,7 +63,7 @@
"\n",
"import uniface\n",
"from uniface.detection import RetinaFace\n",
- "from uniface.privacy import BlurFace, anonymize_faces\n",
+ "from uniface.privacy import BlurFace\n",
"\n",
"print(f'UniFace version: {uniface.__version__}')"
]
@@ -117,9 +117,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "## 4. Quick Start: One-Line Anonymization\n",
+ "## 4. Quick Start: Anonymization\n",
"\n",
- "The simplest way to anonymize faces is using the `anonymize_faces()` function.\n"
+ "Detect faces and blur them using `BlurFace`.\n"
]
},
{
@@ -140,8 +140,12 @@
}
],
"source": [
- "# One-line anonymization with automatic detection\n",
- "anonymized = anonymize_faces(image.copy(), method='pixelate')\n",
+ "# Detect faces and anonymize\n",
+ "detector = RetinaFace()\n",
+ "blurrer = BlurFace(method=\"pixelate\")\n",
+ "\n",
+ "faces = detector.detect(image.copy())\n",
+ "anonymized = blurrer.anonymize(image.copy(), faces)\n",
"\n",
"# Display result\n",
"output = cv2.cvtColor(anonymized, cv2.COLOR_BGR2RGB)\n",
@@ -280,15 +284,14 @@
"\n",
"This notebook demonstrated:\n",
"\n",
- "- ✅ One-line face anonymization with `anonymize_faces()`\n",
- "- ✅ Five different blur methods (gaussian, pixelate, blackout, elliptical, median)\n",
- "- ✅ Automatic face detection and blurring\n",
+ "- \u2705 Five different blur methods (gaussian, pixelate, blackout, elliptical, median)\n",
+ "- \u2705 Automatic face detection and blurring\n",
"\n",
"### Recommended Methods\n",
"\n",
"| Use Case | Method | Parameters |\n",
"|----------|--------|------------|\n",
- "| News media / Publishing | `pixelate` | `pixel_blocks=8-10` |\n",
+ "| News media / Publishing | `pixelate` | `pixel_blocks=10-15` |\n",
"| Social media | `gaussian` or `elliptical` | `blur_strength=3-5` |\n",
"| Maximum privacy | `blackout` | `color=(0,0,0)` |\n",
"| Natural appearance | `elliptical` | `blur_strength=3, margin=20` |\n",
diff --git a/examples/09_face_segmentation.ipynb b/examples/09_face_segmentation.ipynb
index 21bc77c..88113b9 100644
--- a/examples/09_face_segmentation.ipynb
+++ b/examples/09_face_segmentation.ipynb
@@ -198,7 +198,7 @@
"# Parse first face\n",
"if len(faces) > 0 and faces[0].landmarks is not None:\n",
" face = faces[0]\n",
- " mask = parser.parse(image, face.landmarks)\n",
+ " mask = parser.parse(image, landmarks=face.landmarks)\n",
"\n",
" print(f\"Mask shape: {mask.shape}\")\n",
" print(f\"Mask range: [{mask.min():.3f}, {mask.max():.3f}]\")\n",
@@ -251,7 +251,7 @@
"\n",
"for i, blur in enumerate(blur_values):\n",
" parser_test = XSeg(blur_sigma=blur)\n",
- " mask = parser_test.parse(image, landmarks)\n",
+ " mask = parser_test.parse(image, landmarks=landmarks)\n",
"\n",
" axes[i].imshow(mask, cmap=\"gray\")\n",
" axes[i].set_title(f\"blur_sigma={blur}\")\n",
@@ -372,7 +372,7 @@
"face = faces[0]\n",
"\n",
"# XSeg: requires landmarks\n",
- "xseg_mask = parser.parse(image, face.landmarks)\n",
+ "xseg_mask = parser.parse(image, landmarks=face.landmarks)\n",
"\n",
"# BiSeNet: works on bbox crop\n",
"bisenet = BiSeNet()\n",
@@ -431,7 +431,7 @@
"# Load image\n",
"image = cv2.imread(\"../assets/einstien.png\")\n",
"faces = detector.detect(image)\n",
- "mask = parser.parse(image, faces[0].landmarks)\n",
+ "mask = parser.parse(image, landmarks=faces[0].landmarks)\n",
"\n",
"# Extract face only\n",
"mask_3ch = np.stack([mask] * 3, axis=-1)\n",
@@ -469,7 +469,7 @@
"\n",
"XSeg provides face segmentation using landmark-based alignment:\n",
"\n",
- "- **`parse(image, landmarks)`** - Full pipeline: align, segment, warp back\n",
+ "- **`parse(image, landmarks=landmarks)`** - Full pipeline: align, segment, warp back\n",
"- **`parse_aligned(face_crop)`** - For pre-aligned crops\n",
"- **`parse_with_inverse(image, landmarks)`** - Returns mask + crop + inverse matrix\n",
"\n",
diff --git a/pyproject.toml b/pyproject.toml
index a2c5e83..d53b087 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "uniface"
-version = "2.3.0"
+version = "3.0.0"
description = "UniFace: A Comprehensive Library for Face Detection, Recognition, Tracking, Landmark Analysis, Face Parsing, Gaze Estimation, Age, and Gender Detection"
readme = "README.md"
license = "MIT"
@@ -43,9 +43,9 @@ classifiers = [
dependencies = [
"numpy>=1.21.0",
"opencv-python>=4.5.0",
- "onnx>=1.12.0",
"onnxruntime>=1.16.0",
"scikit-image>=0.19.0",
+ "scipy>=1.7.0",
"requests>=2.28.0",
"tqdm>=4.64.0",
]
@@ -57,9 +57,9 @@ gpu = ["onnxruntime-gpu>=1.16.0"]
[project.urls]
Homepage = "https://github.com/yakhyo/uniface"
Repository = "https://github.com/yakhyo/uniface"
-Documentation = "https://github.com/yakhyo/uniface/blob/main/README.md"
-"Quick Start" = "https://github.com/yakhyo/uniface/blob/main/QUICKSTART.md"
-"Model Zoo" = "https://github.com/yakhyo/uniface/blob/main/MODELS.md"
+Documentation = "https://yakhyo.github.io/uniface"
+"Quick Start" = "https://yakhyo.github.io/uniface/quickstart/"
+"Model Zoo" = "https://yakhyo.github.io/uniface/models/"
[build-system]
requires = ["setuptools>=64", "wheel"]
diff --git a/requirements.txt b/requirements.txt
index 5a72aee..33d4223 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,8 +1,7 @@
numpy>=1.21.0
opencv-python>=4.5.0
-onnx>=1.12.0
onnxruntime>=1.16.0
scikit-image>=0.19.0
+scipy>=1.7.0
requests>=2.28.0
-pytest>=7.0.0
tqdm>=4.64.0
diff --git a/tests/test_age_gender.py b/tests/test_age_gender.py
index 4b29b27..bbc4888 100644
--- a/tests/test_age_gender.py
+++ b/tests/test_age_gender.py
@@ -2,7 +2,6 @@
# Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo
-"""Tests for AgeGender attribute predictor."""
from __future__ import annotations
diff --git a/tests/test_draw.py b/tests/test_draw.py
new file mode 100644
index 0000000..b2a8dc2
--- /dev/null
+++ b/tests/test_draw.py
@@ -0,0 +1,61 @@
+# Copyright 2025-2026 Yakhyokhuja Valikhujaev
+# Author: Yakhyokhuja Valikhujaev
+# GitHub: https://github.com/yakhyo
+
+from __future__ import annotations
+
+import numpy as np
+
+from uniface.draw import draw_gaze
+
+
+def _compute_gaze_delta(bbox: np.ndarray, pitch: float, yaw: float) -> tuple[int, int]:
+ """Replicate draw_gaze dx/dy math for verification."""
+ x_min, _, x_max, _ = map(int, bbox[:4])
+ length = x_max - x_min
+ dx = int(-length * np.sin(yaw) * np.cos(pitch))
+ dy = int(-length * np.sin(pitch))
+ return dx, dy
+
+
+def test_draw_gaze_yaw_only_moves_horizontally():
+ """Yaw-only input (pitch=0) should produce horizontal displacement only."""
+ image = np.zeros((200, 200, 3), dtype=np.uint8)
+ bbox = np.array([50, 50, 150, 150], dtype=np.float32)
+
+ yaw = 0.5
+ pitch = 0.0
+ dx, dy = _compute_gaze_delta(bbox, pitch, yaw)
+
+ assert dx != 0, 'Yaw-only should produce horizontal displacement'
+ assert dy == 0, 'Yaw-only should produce zero vertical displacement'
+
+ # Should not raise
+ draw_gaze(image, bbox, pitch, yaw, draw_bbox=False, draw_angles=False)
+
+
+def test_draw_gaze_pitch_only_moves_vertically():
+ """Pitch-only input (yaw=0) should produce vertical displacement only."""
+ image = np.zeros((200, 200, 3), dtype=np.uint8)
+ bbox = np.array([50, 50, 150, 150], dtype=np.float32)
+
+ yaw = 0.0
+ pitch = 0.5
+ dx, dy = _compute_gaze_delta(bbox, pitch, yaw)
+
+ assert dx == 0, 'Pitch-only should produce zero horizontal displacement'
+ assert dy != 0, 'Pitch-only should produce vertical displacement'
+
+ # Should not raise
+ draw_gaze(image, bbox, pitch, yaw, draw_bbox=False, draw_angles=False)
+
+
+def test_draw_gaze_modifies_image():
+ """draw_gaze should modify the image in place."""
+ image = np.zeros((200, 200, 3), dtype=np.uint8)
+ bbox = np.array([50, 50, 150, 150], dtype=np.float32)
+
+ original = image.copy()
+ draw_gaze(image, bbox, 0.3, 0.3)
+
+ assert not np.array_equal(image, original), 'draw_gaze should modify the image'
diff --git a/tests/test_factory.py b/tests/test_factory.py
index b2fffaa..7ab71ef 100644
--- a/tests/test_factory.py
+++ b/tests/test_factory.py
@@ -2,7 +2,6 @@
# Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo
-"""Tests for factory functions (create_detector, create_recognizer, etc.)."""
from __future__ import annotations
@@ -13,10 +12,10 @@ from uniface import (
create_detector,
create_landmarker,
create_recognizer,
- detect_faces,
list_available_detectors,
)
from uniface.constants import RetinaFaceWeights, SCRFDWeights
+from uniface.spoofing import MiniFASNet, create_spoofer
# create_detector tests
@@ -123,62 +122,6 @@ def test_create_landmarker_invalid_method():
create_landmarker('invalid_method')
-# detect_faces tests
-def test_detect_faces_retinaface():
- """
- Test high-level detect_faces function with RetinaFace.
- """
- mock_image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
- faces = detect_faces(mock_image, method='retinaface')
-
- assert isinstance(faces, list), 'detect_faces should return a list'
-
-
-def test_detect_faces_scrfd():
- """
- Test high-level detect_faces function with SCRFD.
- """
- mock_image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
- faces = detect_faces(mock_image, method='scrfd')
-
- assert isinstance(faces, list), 'detect_faces should return a list'
-
-
-def test_detect_faces_with_threshold():
- """
- Test detect_faces with custom confidence threshold.
- """
- mock_image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
- faces = detect_faces(mock_image, method='retinaface', confidence_threshold=0.8)
-
- assert isinstance(faces, list), 'detect_faces should return a list'
-
- # All detections should respect threshold
- for face in faces:
- assert face.confidence >= 0.8, 'All detections should meet confidence threshold'
-
-
-def test_detect_faces_default_method():
- """
- Test detect_faces with default method (should use retinaface).
- """
- mock_image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
- faces = detect_faces(mock_image) # No method specified
-
- assert isinstance(faces, list), 'detect_faces should return a list with default method'
-
-
-def test_detect_faces_empty_image():
- """
- Test detect_faces on a blank image.
- """
- empty_image = np.zeros((640, 640, 3), dtype=np.uint8)
- faces = detect_faces(empty_image, method='retinaface')
-
- assert isinstance(faces, list), 'Should return a list even for empty image'
- assert len(faces) == 0, 'Should detect no faces in blank image'
-
-
# list_available_detectors tests
def test_list_available_detectors():
"""
@@ -280,3 +223,16 @@ def test_factory_returns_correct_types():
assert isinstance(detector, RetinaFace), 'Should return RetinaFace instance'
assert isinstance(recognizer, ArcFace), 'Should return ArcFace instance'
assert isinstance(landmarker, Landmark106), 'Should return Landmark106 instance'
+
+
+# create_spoofer tests
+def test_create_spoofer_default():
+ """Test creating a spoofer with default parameters."""
+ spoofer = create_spoofer()
+ assert isinstance(spoofer, MiniFASNet), 'Should return MiniFASNet instance'
+
+
+def test_create_spoofer_with_providers():
+ """Test that create_spoofer forwards providers kwarg without TypeError."""
+ spoofer = create_spoofer(providers=['CPUExecutionProvider'])
+ assert isinstance(spoofer, MiniFASNet), 'Should return MiniFASNet instance'
diff --git a/tests/test_landmark.py b/tests/test_landmark.py
index e73b561..d014983 100644
--- a/tests/test_landmark.py
+++ b/tests/test_landmark.py
@@ -2,7 +2,6 @@
# Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo
-"""Tests for 106-point facial landmark detector."""
from __future__ import annotations
diff --git a/tests/test_parsing.py b/tests/test_parsing.py
index e654cb4..273a740 100644
--- a/tests/test_parsing.py
+++ b/tests/test_parsing.py
@@ -2,7 +2,6 @@
# Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo
-"""Tests for face parsing models (BiSeNet and XSeg)."""
from __future__ import annotations
@@ -209,7 +208,7 @@ def test_xseg_parse_with_landmarks():
)
# Parse
- mask = parser.parse(image, landmarks)
+ mask = parser.parse(image, landmarks=landmarks)
assert mask.shape == (480, 640)
assert mask.dtype == np.float32
@@ -226,7 +225,7 @@ def test_xseg_parse_invalid_landmarks():
invalid_landmarks = np.array([[0, 0], [1, 1], [2, 2]])
with pytest.raises(ValueError, match='Landmarks must have shape'):
- parser.parse(image, invalid_landmarks)
+ parser.parse(image, landmarks=invalid_landmarks)
def test_xseg_parse_with_inverse():
diff --git a/tests/test_recognition.py b/tests/test_recognition.py
index ac32a2e..db0a789 100644
--- a/tests/test_recognition.py
+++ b/tests/test_recognition.py
@@ -2,7 +2,6 @@
# Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo
-"""Tests for face recognition models (ArcFace, MobileFace, SphereFace)."""
from __future__ import annotations
diff --git a/tests/test_retinaface.py b/tests/test_retinaface.py
index 590174a..7c1341a 100644
--- a/tests/test_retinaface.py
+++ b/tests/test_retinaface.py
@@ -2,7 +2,6 @@
# Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo
-"""Tests for RetinaFace detector."""
from __future__ import annotations
diff --git a/tests/test_scrfd.py b/tests/test_scrfd.py
index 6c849f7..4e5eb85 100644
--- a/tests/test_scrfd.py
+++ b/tests/test_scrfd.py
@@ -2,7 +2,6 @@
# Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo
-"""Tests for SCRFD detector."""
from __future__ import annotations
diff --git a/tests/test_types.py b/tests/test_types.py
index 9a05cd8..3ef6bcb 100644
--- a/tests/test_types.py
+++ b/tests/test_types.py
@@ -2,7 +2,6 @@
# Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo
-"""Tests for UniFace type definitions (dataclasses)."""
from __future__ import annotations
diff --git a/tests/test_utils.py b/tests/test_utils.py
index 5f0dc21..365c59a 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -2,7 +2,6 @@
# Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo
-"""Tests for utility functions (compute_similarity, face_alignment, etc.)."""
from __future__ import annotations
diff --git a/tools/README.md b/tools/README.md
index a910483..e76b3a1 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -26,7 +26,7 @@ CLI utilities for testing and running UniFace features.
## Unified `--source` Pattern
-All tools use a unified `--source` argument that accepts:
+Most tools use a unified `--source` argument that accepts:
- **Image path**: `--source photo.jpg`
- **Video path**: `--source video.mp4`
- **Camera ID**: `--source 0` (default webcam), `--source 1` (external camera)
diff --git a/tools/anonymize.py b/tools/anonymize.py
index f066749..82cd010 100644
--- a/tools/anonymize.py
+++ b/tools/anonymize.py
@@ -155,19 +155,19 @@ def main():
epilog="""
Examples:
# Anonymize image with pixelation (default)
- python run_anonymization.py --source photo.jpg
+ python tools/anonymize.py --source photo.jpg
# Use Gaussian blur with custom strength
- python run_anonymization.py --source photo.jpg --method gaussian --blur-strength 5.0
+ python tools/anonymize.py --source photo.jpg --method gaussian --blur-strength 5.0
# Real-time webcam anonymization
- python run_anonymization.py --source 0 --method pixelate
+ python tools/anonymize.py --source 0 --method pixelate
# Black boxes for maximum privacy
- python run_anonymization.py --source photo.jpg --method blackout
+ python tools/anonymize.py --source photo.jpg --method blackout
# Custom pixelation intensity
- python run_anonymization.py --source photo.jpg --method pixelate --pixel-blocks 5
+ python tools/anonymize.py --source photo.jpg --method pixelate --pixel-blocks 5
""",
)
diff --git a/tools/detect.py b/tools/detect.py
index d802ac6..e975a33 100644
--- a/tools/detect.py
+++ b/tools/detect.py
@@ -163,7 +163,11 @@ def main():
parser = argparse.ArgumentParser(description='Run face detection')
parser.add_argument('--source', type=str, required=True, help='Image/video path or camera ID (0, 1, ...)')
parser.add_argument(
- '--method', type=str, default='retinaface', choices=['retinaface', 'scrfd', 'yolov5face', 'yolov8face']
+ '--detector',
+ '--method',
+ type=str,
+ default='retinaface',
+ choices=['retinaface', 'scrfd', 'yolov5face', 'yolov8face'],
)
parser.add_argument('--threshold', type=float, default=0.25, help='Visualization threshold')
parser.add_argument('--preview', action='store_true', help='Show live preview during video processing')
@@ -172,11 +176,11 @@ def main():
args = parser.parse_args()
# Initialize detector
- if args.method == 'retinaface':
+ if args.detector == 'retinaface':
detector = RetinaFace()
- elif args.method == 'scrfd':
+ elif args.detector == 'scrfd':
detector = SCRFD()
- elif args.method == 'yolov5face':
+ elif args.detector == 'yolov5face':
from uniface.constants import YOLOv5FaceWeights
detector = YOLOv5Face(model_name=YOLOv5FaceWeights.YOLOV5M)
diff --git a/tools/parse.py b/tools/parse.py
index 18c55bf..f731fb6 100644
--- a/tools/parse.py
+++ b/tools/parse.py
@@ -209,7 +209,7 @@ def main():
args = parser_arg.parse_args()
detector = RetinaFace()
- parser = BiSeNet(model_name=ParsingWeights.RESNET34)
+ parser = BiSeNet(model_name=args.model)
source_type = get_source_type(args.source)
diff --git a/tools/recognize.py b/tools/recognize.py
index 1b092b1..087bd7a 100644
--- a/tools/recognize.py
+++ b/tools/recognize.py
@@ -41,7 +41,7 @@ def run_inference(detector, recognizer, image_path: str):
print(f'Detected {len(faces)} face(s). Extracting embedding for the first face...')
- landmarks = faces[0]['landmarks'] # 5-point landmarks for alignment (already np.ndarray)
+ landmarks = faces[0].landmarks # 5-point landmarks for alignment (already np.ndarray)
embedding = recognizer.get_embedding(image, landmarks)
norm_embedding = recognizer.get_normalized_embedding(image, landmarks) # L2 normalized
@@ -65,8 +65,8 @@ def compare_faces(detector, recognizer, image1_path: str, image2_path: str, thre
print('Error: No faces detected in one or both images')
return
- landmarks1 = faces1[0]['landmarks']
- landmarks2 = faces2[0]['landmarks']
+ landmarks1 = faces1[0].landmarks
+ landmarks2 = faces2[0].landmarks
embedding1 = recognizer.get_normalized_embedding(img1, landmarks1)
embedding2 = recognizer.get_normalized_embedding(img2, landmarks2)
diff --git a/tools/xseg.py b/tools/xseg.py
index c8b02ee..7eb23bd 100644
--- a/tools/xseg.py
+++ b/tools/xseg.py
@@ -59,7 +59,7 @@ def process_image(
print(f' Face {i + 1}: skipped (no landmarks)')
continue
- mask = parser.parse(image, face.landmarks)
+ mask = parser.parse(image, landmarks=face.landmarks)
full_mask = np.maximum(full_mask, mask)
print(f' Face {i + 1}: done')
@@ -121,7 +121,7 @@ def process_video(
for face in faces:
if face.landmarks is None:
continue
- mask = parser.parse(frame, face.landmarks)
+ mask = parser.parse(frame, landmarks=face.landmarks)
full_mask = np.maximum(full_mask, mask)
# Apply visualization
@@ -169,7 +169,7 @@ def run_camera(
for face in faces:
if face.landmarks is None:
continue
- mask = parser.parse(frame, face.landmarks)
+ mask = parser.parse(frame, landmarks=face.landmarks)
full_mask = np.maximum(full_mask, mask)
# Apply visualization
diff --git a/uniface/__init__.py b/uniface/__init__.py
index c849ac1..d67ae7f 100644
--- a/uniface/__init__.py
+++ b/uniface/__init__.py
@@ -29,39 +29,31 @@ from __future__ import annotations
__license__ = 'MIT'
__author__ = 'Yakhyokhuja Valikhujaev'
-__version__ = '2.3.0'
+__version__ = '3.0.0'
from uniface.face_utils import compute_similarity, face_alignment
from uniface.log import Logger, enable_logging
from uniface.model_store import download_models, get_cache_dir, set_cache_dir, verify_model_weights
from .analyzer import FaceAnalyzer
-from .attribute import AgeGender, FairFace
+from .attribute import AgeGender, Emotion, FairFace
from .detection import (
SCRFD,
RetinaFace,
YOLOv5Face,
YOLOv8Face,
create_detector,
- detect_faces,
list_available_detectors,
)
from .gaze import MobileGaze, create_gaze_estimator
from .landmark import Landmark106, create_landmarker
from .parsing import BiSeNet, XSeg, create_face_parser
-from .privacy import BlurFace, anonymize_faces
+from .privacy import BlurFace
from .recognition import AdaFace, ArcFace, MobileFace, SphereFace, create_recognizer
from .spoofing import MiniFASNet, create_spoofer
from .tracking import BYTETracker
from .types import AttributeResult, EmotionResult, Face, GazeResult, SpoofingResult
-# Optional: Emotion requires PyTorch
-Emotion: type | None
-try:
- from .attribute import Emotion
-except ImportError:
- Emotion = None
-
__all__ = [
# Metadata
'__author__',
@@ -77,7 +69,6 @@ __all__ = [
'create_landmarker',
'create_recognizer',
'create_spoofer',
- 'detect_faces',
'list_available_detectors',
# Detection models
'RetinaFace',
@@ -110,7 +101,6 @@ __all__ = [
'BYTETracker',
# Privacy
'BlurFace',
- 'anonymize_faces',
# Utilities
'Logger',
'compute_similarity',
diff --git a/uniface/attribute/__init__.py b/uniface/attribute/__init__.py
index 84ccd03..5400a1b 100644
--- a/uniface/attribute/__init__.py
+++ b/uniface/attribute/__init__.py
@@ -12,18 +12,27 @@ from uniface.attribute.age_gender import AgeGender
from uniface.attribute.base import Attribute
from uniface.attribute.fairface import FairFace
from uniface.constants import AgeGenderWeights, DDAMFNWeights, FairFaceWeights
-from uniface.types import AttributeResult, EmotionResult, Face
+from uniface.types import AttributeResult, EmotionResult
-# Emotion requires PyTorch - make it optional
try:
from uniface.attribute.emotion import Emotion
_EMOTION_AVAILABLE = True
except ImportError:
- Emotion = None
_EMOTION_AVAILABLE = False
-# Public API for the attribute module
+ class Emotion(Attribute): # type: ignore[no-redef]
+ """Stub for Emotion when PyTorch is not installed."""
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ raise ImportError("Emotion requires optional dependency 'torch'. Install with: pip install torch")
+
+ def _initialize_model(self) -> None: ...
+ def preprocess(self, image: np.ndarray, *args: Any) -> Any: ...
+ def postprocess(self, prediction: Any) -> Any: ...
+ def predict(self, image: np.ndarray, *args: Any) -> Any: ...
+
+
__all__ = [
'AgeGender',
'AttributeResult',
@@ -31,16 +40,13 @@ __all__ = [
'EmotionResult',
'FairFace',
'create_attribute_predictor',
- 'predict_attributes',
]
-# A mapping from model enums to their corresponding attribute classes
_ATTRIBUTE_MODELS = {
**dict.fromkeys(AgeGenderWeights, AgeGender),
**dict.fromkeys(FairFaceWeights, FairFace),
}
-# Add Emotion models only if PyTorch is available
if _EMOTION_AVAILABLE:
_ATTRIBUTE_MODELS.update(dict.fromkeys(DDAMFNWeights, Emotion))
@@ -48,21 +54,16 @@ if _EMOTION_AVAILABLE:
def create_attribute_predictor(
model_name: AgeGenderWeights | DDAMFNWeights | FairFaceWeights, **kwargs: Any
) -> Attribute:
- """
- Factory function to create an attribute predictor instance.
-
- This high-level API simplifies the creation of attribute models by
- dynamically selecting the correct class based on the provided model enum.
+ """Factory function to create an attribute predictor instance.
Args:
model_name: The enum corresponding to the desired attribute model
- (e.g., AgeGenderWeights.DEFAULT, DDAMFNWeights.AFFECNET7,
- or FairFaceWeights.DEFAULT).
- **kwargs: Additional keyword arguments to pass to the model's constructor.
+ (e.g., AgeGenderWeights.DEFAULT, DDAMFNWeights.AFFECNET7,
+ or FairFaceWeights.DEFAULT).
+ **kwargs: Additional keyword arguments passed to the model constructor.
Returns:
- An initialized instance of an Attribute predictor class
- (e.g., AgeGender, FairFace, or Emotion).
+ An initialized Attribute predictor (AgeGender, FairFace, or Emotion).
Raises:
ValueError: If the provided model_name is not a supported enum.
@@ -75,40 +76,4 @@ def create_attribute_predictor(
f'Please choose from AgeGenderWeights, FairFaceWeights, or DDAMFNWeights.'
)
- # Pass model_name to the constructor, as some classes might need it
return model_class(model_name=model_name, **kwargs)
-
-
-def predict_attributes(image: np.ndarray, faces: list[Face], predictor: Attribute) -> list[Face]:
- """
- High-level API to predict attributes for multiple detected faces.
-
- This function iterates through a list of Face objects, runs the
- specified attribute predictor on each one, and updates the Face
- objects with the predicted attributes.
-
- Args:
- image (np.ndarray): The full input image in BGR format.
- faces (List[Face]): A list of Face objects from face detection.
- predictor (Attribute): An initialized attribute predictor instance,
- created by `create_attribute_predictor`.
-
- Returns:
- List[Face]: The list of Face objects with updated attribute fields.
- """
- for face in faces:
- if isinstance(predictor, AgeGender):
- result = predictor(image, face.bbox)
- face.gender = result.gender
- face.age = result.age
- elif isinstance(predictor, FairFace):
- result = predictor(image, face.bbox)
- face.gender = result.gender
- face.age_group = result.age_group
- face.race = result.race
- elif isinstance(predictor, Emotion):
- result = predictor(image, face.landmarks)
- face.emotion = result.emotion
- face.emotion_confidence = result.confidence
-
- return faces
diff --git a/uniface/attribute/emotion.py b/uniface/attribute/emotion.py
index 62b184b..854aa89 100644
--- a/uniface/attribute/emotion.py
+++ b/uniface/attribute/emotion.py
@@ -28,17 +28,17 @@ class Emotion(Attribute):
def __init__(
self,
- model_weights: DDAMFNWeights = DDAMFNWeights.AFFECNET7,
+ model_name: DDAMFNWeights = DDAMFNWeights.AFFECNET7,
input_size: tuple[int, int] = (112, 112),
) -> None:
"""
Initializes the emotion recognition model.
Args:
- model_weights (DDAMFNWeights): The enum for the model weights to load.
+ model_name (DDAMFNWeights): The enum for the model weights to load.
input_size (Tuple[int, int]): The expected input size for the model.
"""
- Logger.info(f'Initializing Emotion with model={model_weights.name}')
+ Logger.info(f'Initializing Emotion with model={model_name.name}')
if torch.backends.mps.is_available():
self.device = torch.device('mps')
@@ -48,7 +48,7 @@ class Emotion(Attribute):
self.device = torch.device('cpu')
self.input_size = input_size
- self.model_path = verify_model_weights(model_weights)
+ self.model_path = verify_model_weights(model_name)
# Define emotion labels based on the selected model
self.emotion_labels = [
@@ -60,7 +60,7 @@ class Emotion(Attribute):
'Disgust',
'Angry',
]
- if model_weights == DDAMFNWeights.AFFECNET8:
+ if model_name == DDAMFNWeights.AFFECNET8:
self.emotion_labels.append('Contempt')
self._initialize_model()
diff --git a/uniface/constants.py b/uniface/constants.py
index 52eb9af..514bc00 100644
--- a/uniface/constants.py
+++ b/uniface/constants.py
@@ -272,11 +272,11 @@ MODEL_SHA256: dict[Enum, str] = {
# Landmark
LandmarkWeights.DEFAULT: 'f001b856447c413801ef5c42091ed0cd516fcd21f2d6b79635b1e733a7109dbf',
# MobileGaze (trained on Gaze360)
- GazeWeights.RESNET18: '23d5d7e4f6f40dce8c35274ce9d08b45b9e22cbaaf5af73182f473229d713d31',
- GazeWeights.RESNET34: '4457ee5f7acd1a5ab02da4b61f02fc3a0b17adbf3844dd0ba3cd4288f2b5e1de',
- GazeWeights.RESNET50: 'e1eaf98f5ec7c89c6abe7cfe39f7be83e747163f98d1ff945c0603b3c521be22',
- GazeWeights.MOBILENET_V2: 'fdcdb84e3e6421b5a79e8f95139f249fc258d7f387eed5ddac2b80a9a15ce076',
- GazeWeights.MOBILEONE_S0: 'c0b5a4f4a0ffd24f76ab3c1452354bb2f60110899fd9a88b464c75bafec0fde8',
+ GazeWeights.RESNET18: '404fec1efd07ff49f981e47f461c20c2627119e465ec441bbd1c067d3f16e657',
+ GazeWeights.RESNET34: 'c8e6b14f6095d2425241b9302aa663d9a23b7dfb9d43941352b718c91dc7f2cf',
+ GazeWeights.RESNET50: 'bb28d421565adc4dfb665742f8fc80bdef36dd8caa0c87e040e0937f9fdca9a6',
+ GazeWeights.MOBILENET_V2: 'b81312df85c7ac1c1b5f78c573620d22c2719cb839650e15f12dc7eecb7744a4',
+ GazeWeights.MOBILEONE_S0: '8b4fdc4e3da44733c9a82e7776b411e4a39f94e8e285aee0fc85a548a55f7d9f',
# Face Parsing
ParsingWeights.RESNET18: '0d9bd318e46987c3bdbfacae9e2c0f461cae1c6ac6ea6d43bbe541a91727e33f',
ParsingWeights.RESNET34: '5b805bba7b5660ab7070b5a381dcf75e5b3e04199f1e9387232a77a00095102e',
diff --git a/uniface/detection/__init__.py b/uniface/detection/__init__.py
index 3fd6085..71f0f78 100644
--- a/uniface/detection/__init__.py
+++ b/uniface/detection/__init__.py
@@ -6,9 +6,12 @@ from __future__ import annotations
from typing import Any
-import numpy as np
-
-from uniface.types import Face
+from uniface.constants import (
+ RetinaFaceWeights,
+ SCRFDWeights,
+ YOLOv5FaceWeights,
+ YOLOv8FaceWeights,
+)
from .base import BaseDetector
from .retinaface import RetinaFace
@@ -16,48 +19,6 @@ from .scrfd import SCRFD
from .yolov5 import YOLOv5Face
from .yolov8 import YOLOv8Face
-# Global cache for detector instances (keyed by method name + config hash)
-_detector_cache: dict[str, BaseDetector] = {}
-
-
-def detect_faces(image: np.ndarray, method: str = 'retinaface', **kwargs: Any) -> list[Face]:
- """High-level face detection function.
-
- Detects faces in an image using the specified detection method.
- Results are cached for repeated calls with the same configuration.
-
- Args:
- image: Input image as numpy array with shape (H, W, C) in BGR format.
- method: Detection method to use. Options: 'retinaface', 'scrfd', 'yolov5face', 'yolov8face'.
- **kwargs: Additional arguments passed to the detector.
-
- Returns:
- A list of Face objects, each containing:
- - bbox: [x1, y1, x2, y2] bounding box coordinates.
- - confidence: The confidence score of the detection.
- - landmarks: 5-point facial landmarks with shape (5, 2).
-
- Example:
- >>> from uniface import detect_faces
- >>> import cv2
- >>> image = cv2.imread('your_image.jpg')
- >>> faces = detect_faces(image, method='retinaface', confidence_threshold=0.8)
- >>> for face in faces:
- ... print(f'Found face with confidence: {face.confidence}')
- ... print(f'BBox: {face.bbox}')
- """
- method_name = method.lower()
-
- sorted_kwargs = sorted(kwargs.items())
- cache_key = f'{method_name}_{sorted_kwargs!s}'
-
- if cache_key not in _detector_cache:
- # Pass kwargs to create the correctly configured detector
- _detector_cache[cache_key] = create_detector(method, **kwargs)
-
- detector = _detector_cache[cache_key]
- return detector.detect(image)
-
def create_detector(method: str = 'retinaface', **kwargs: Any) -> BaseDetector:
"""Factory function to create face detectors.
@@ -122,7 +83,7 @@ def list_available_detectors() -> dict[str, dict[str, Any]]:
'supports_landmarks': True,
'paper': 'https://arxiv.org/abs/1905.00641',
'default_params': {
- 'model_name': 'mnet_v2',
+ 'model_name': RetinaFaceWeights.MNET_V2.value,
'confidence_threshold': 0.5,
'nms_threshold': 0.4,
'input_size': (640, 640),
@@ -133,7 +94,7 @@ def list_available_detectors() -> dict[str, dict[str, Any]]:
'supports_landmarks': True,
'paper': 'https://arxiv.org/abs/2105.04714',
'default_params': {
- 'model_name': 'scrfd_10g_kps',
+ 'model_name': SCRFDWeights.SCRFD_10G_KPS.value,
'confidence_threshold': 0.5,
'nms_threshold': 0.4,
'input_size': (640, 640),
@@ -144,9 +105,9 @@ def list_available_detectors() -> dict[str, dict[str, Any]]:
'supports_landmarks': True,
'paper': 'https://arxiv.org/abs/2105.12931',
'default_params': {
- 'model_name': 'yolov5s_face',
- 'confidence_threshold': 0.25,
- 'nms_threshold': 0.45,
+ 'model_name': YOLOv5FaceWeights.YOLOV5S.value,
+ 'confidence_threshold': 0.6,
+ 'nms_threshold': 0.5,
'input_size': 640,
},
},
@@ -155,7 +116,7 @@ def list_available_detectors() -> dict[str, dict[str, Any]]:
'supports_landmarks': True,
'paper': 'https://github.com/derronqi/yolov8-face',
'default_params': {
- 'model_name': 'yolov8n_face',
+ 'model_name': YOLOv8FaceWeights.YOLOV8N.value,
'confidence_threshold': 0.5,
'nms_threshold': 0.45,
'input_size': 640,
@@ -171,6 +132,5 @@ __all__ = [
'YOLOv5Face',
'YOLOv8Face',
'create_detector',
- 'detect_faces',
'list_available_detectors',
]
diff --git a/uniface/draw.py b/uniface/draw.py
index d9e2371..a675d73 100644
--- a/uniface/draw.py
+++ b/uniface/draw.py
@@ -326,8 +326,8 @@ def draw_gaze(
# Calculate the direction of the gaze
length = x_max - x_min
- dx = int(-length * np.sin(pitch) * np.cos(yaw))
- dy = int(-length * np.sin(yaw))
+ dx = int(-length * np.sin(yaw) * np.cos(pitch))
+ dy = int(-length * np.sin(pitch))
# Draw gaze arrow
center_radius = max(line_thickness + 1, 4)
@@ -373,16 +373,16 @@ def draw_tracks(
Args:
image: Input image to draw on (modified in-place).
- faces: List of Face objects (with ``track_id`` assigned by FaceTracker).
+ faces: List of Face objects (with ``track_id`` assigned by BYTETracker).
draw_landmarks: Whether to draw facial landmarks. Defaults to True.
draw_id: Whether to draw track ID labels. Defaults to True.
corner_bbox: Use corner-style bounding boxes. Defaults to True.
Example:
- >>> from uniface import FaceTracker, RetinaFace
+ >>> from uniface import BYTETracker, RetinaFace
>>> from uniface.draw import draw_tracks
- >>> tracker = FaceTracker(RetinaFace())
- >>> faces = tracker.update(frame)
+ >>> detector = RetinaFace()
+ >>> tracker = BYTETracker()
>>> draw_tracks(image=frame, faces=faces)
"""
untracked_color = (128, 128, 128)
diff --git a/uniface/gaze/__init__.py b/uniface/gaze/__init__.py
index 48b4158..3718c50 100644
--- a/uniface/gaze/__init__.py
+++ b/uniface/gaze/__init__.py
@@ -31,7 +31,7 @@ def create_gaze_estimator(method: str = 'mobilegaze', **kwargs) -> BaseGazeEstim
ValueError: If the specified `method` is not supported.
Examples:
- >>> # Create the default MobileGaze estimator (ResNet18 backbone)
+ >>> # Create the default MobileGaze estimator (ResNet34 backbone)
>>> estimator = create_gaze_estimator()
>>> # Create with MobileNetV2 backbone
diff --git a/uniface/gaze/models.py b/uniface/gaze/models.py
index 9c8781e..bb532d0 100644
--- a/uniface/gaze/models.py
+++ b/uniface/gaze/models.py
@@ -106,7 +106,7 @@ class MobileGaze(BaseGazeEstimator):
self.output_names = [output.name for output in outputs]
if len(self.output_names) != 2:
- raise ValueError(f'Expected 2 output nodes (pitch, yaw), got {len(self.output_names)}')
+ raise ValueError(f'Expected 2 output nodes (yaw, pitch), got {len(self.output_names)}')
Logger.info(f'MobileGaze initialized with input size {self.input_size}')
@@ -161,19 +161,19 @@ class MobileGaze(BaseGazeEstimator):
Returns:
GazeResult: Result containing pitch and yaw angles in radians.
"""
- pitch_logits, yaw_logits = outputs
+ yaw_logits, pitch_logits = outputs
# Convert logits to probabilities
- pitch_probs = self._softmax(pitch_logits)
yaw_probs = self._softmax(yaw_logits)
+ pitch_probs = self._softmax(pitch_logits)
# Compute expected bin index (soft-argmax)
- pitch_deg = np.sum(pitch_probs * self._idx_tensor, axis=1) * self._binwidth - self._angle_offset
yaw_deg = np.sum(yaw_probs * self._idx_tensor, axis=1) * self._binwidth - self._angle_offset
+ pitch_deg = np.sum(pitch_probs * self._idx_tensor, axis=1) * self._binwidth - self._angle_offset
# Convert degrees to radians
- pitch = float(np.radians(pitch_deg[0]))
yaw = float(np.radians(yaw_deg[0]))
+ pitch = float(np.radians(pitch_deg[0]))
return GazeResult(pitch=pitch, yaw=yaw)
diff --git a/uniface/landmark/__init__.py b/uniface/landmark/__init__.py
index e2a20e5..d1dd9ea 100644
--- a/uniface/landmark/__init__.py
+++ b/uniface/landmark/__init__.py
@@ -11,17 +11,18 @@ def create_landmarker(method: str = '2d106det', **kwargs) -> BaseLandmarker:
Factory function to create facial landmark predictors.
Args:
- method (str): Landmark prediction method. Options: '106'.
+ method (str): Landmark prediction method.
+ Options: '2d106det' (default), 'landmark106', '106'.
**kwargs: Model-specific parameters.
Returns:
Initialized landmarker instance.
"""
method = method.lower()
- if method == '2d106det':
+ if method in ('2d106det', 'landmark106', '106'):
return Landmark106(**kwargs)
else:
- available = ['2d106det']
+ available = ['2d106det', 'landmark106', '106']
raise ValueError(f"Unsupported method: '{method}'. Available: {available}")
diff --git a/uniface/model_store.py b/uniface/model_store.py
index a015744..cec1b8a 100644
--- a/uniface/model_store.py
+++ b/uniface/model_store.py
@@ -64,7 +64,7 @@ def set_cache_dir(path: str) -> None:
Logger.info(f'Cache directory set to: {path}')
-def verify_model_weights(model_name: Enum, root: str = '~/.uniface/models') -> str:
+def verify_model_weights(model_name: Enum, root: str | None = None) -> str:
"""Ensure model weights are present, downloading and verifying them if necessary.
Given a model identifier from an Enum class (e.g., `RetinaFaceWeights.MNET_V2`),
@@ -75,7 +75,7 @@ def verify_model_weights(model_name: Enum, root: str = '~/.uniface/models') -> s
Args:
model_name: Model weight identifier enum (e.g., `RetinaFaceWeights.MNET_V2`).
root: Directory to store or locate the model weights.
- Defaults to '~/.uniface/models'.
+ If None, uses the cache directory from :func:`get_cache_dir`.
Returns:
Absolute path to the verified model weights file.
@@ -92,7 +92,7 @@ def verify_model_weights(model_name: Enum, root: str = '~/.uniface/models') -> s
'/home/user/.uniface/models/retinaface_mnet_v2.onnx'
"""
- root = get_cache_dir()
+ root = os.path.expanduser(root) if root is not None else get_cache_dir()
os.makedirs(root, exist_ok=True)
# Keep model_name as enum for dictionary lookup
diff --git a/uniface/parsing/base.py b/uniface/parsing/base.py
index 2472f6b..fe987b4 100644
--- a/uniface/parsing/base.py
+++ b/uniface/parsing/base.py
@@ -2,6 +2,8 @@
# Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo
+from __future__ import annotations
+
from abc import ABC, abstractmethod
import numpy as np
@@ -69,7 +71,7 @@ class BaseFaceParser(ABC):
raise NotImplementedError('Subclasses must implement the postprocess method.')
@abstractmethod
- def parse(self, face_image: np.ndarray) -> np.ndarray:
+ def parse(self, image: np.ndarray, *, landmarks: np.ndarray | None = None) -> np.ndarray:
"""
Perform end-to-end face parsing on a face image.
@@ -77,9 +79,11 @@ class BaseFaceParser(ABC):
running inference, and postprocessing to return the segmentation mask.
Args:
- face_image (np.ndarray): A face image in BGR format.
- The face should be roughly centered and
- well-framed within the image.
+ image (np.ndarray): A face image in BGR format.
+ The face should be roughly centered and well-framed within the image.
+ landmarks (np.ndarray | None): Optional 5-point facial landmarks with
+ shape (5, 2). Required by some parsers (e.g., XSeg) for face alignment.
+ Ignored by parsers that do not need landmarks (e.g., BiSeNet).
Returns:
np.ndarray: Segmentation mask with the same size as input image,
@@ -92,14 +96,15 @@ class BaseFaceParser(ABC):
"""
raise NotImplementedError('Subclasses must implement the parse method.')
- def __call__(self, face_image: np.ndarray) -> np.ndarray:
+ def __call__(self, image: np.ndarray, *, landmarks: np.ndarray | None = None) -> np.ndarray:
"""
Provides a convenient, callable shortcut for the `parse` method.
Args:
- face_image (np.ndarray): A face image in BGR format.
+ image (np.ndarray): A face image in BGR format.
+ landmarks (np.ndarray | None): Optional 5-point facial landmarks.
Returns:
np.ndarray: Segmentation mask with the same size as input image.
"""
- return self.parse(face_image)
+ return self.parse(image, landmarks=landmarks)
diff --git a/uniface/parsing/bisenet.py b/uniface/parsing/bisenet.py
index 3a9ca60..125d645 100644
--- a/uniface/parsing/bisenet.py
+++ b/uniface/parsing/bisenet.py
@@ -2,6 +2,7 @@
# Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo
+from __future__ import annotations
import cv2
import numpy as np
@@ -149,21 +150,26 @@ class BiSeNet(BaseFaceParser):
return restored_mask
- def parse(self, face_image: np.ndarray) -> np.ndarray:
+ def parse(self, image: np.ndarray, *, landmarks: np.ndarray | None = None) -> np.ndarray:
"""
Perform end-to-end face parsing on a face image.
This method orchestrates the full pipeline: preprocessing the input,
running inference, and postprocessing to return the segmentation mask.
+ BiSeNet operates on face crops and does not require landmarks.
+ The ``landmarks`` parameter is accepted for API compatibility but ignored.
+
Args:
- face_image (np.ndarray): A face image in BGR format.
+ image (np.ndarray): A face image in BGR format.
+ landmarks (np.ndarray | None): Ignored. Accepted for interface
+ compatibility with :class:`BaseFaceParser`.
Returns:
np.ndarray: Segmentation mask with the same size as input image.
"""
- original_size = (face_image.shape[1], face_image.shape[0]) # (width, height)
- input_tensor = self.preprocess(face_image)
+ original_size = (image.shape[1], image.shape[0]) # (width, height)
+ input_tensor = self.preprocess(image)
outputs = self.session.run(self.output_names, {self.input_name: input_tensor})
return self.postprocess(outputs[0], original_size)
diff --git a/uniface/parsing/xseg.py b/uniface/parsing/xseg.py
index f5ca76a..f8e18ba 100644
--- a/uniface/parsing/xseg.py
+++ b/uniface/parsing/xseg.py
@@ -54,7 +54,7 @@ class XSeg(BaseFaceParser):
>>> faces = detector.detect(image)
>>> for face in faces:
... if face.landmarks is not None:
- ... mask = parser.parse(image, face.landmarks)
+ ... mask = parser.parse(image, landmarks=face.landmarks)
... print(f'Mask shape: {mask.shape}')
"""
@@ -151,20 +151,28 @@ class XSeg(BaseFaceParser):
return mask
- def parse(self, image: np.ndarray, landmarks: np.ndarray) -> np.ndarray:
+ def parse(self, image: np.ndarray, *, landmarks: np.ndarray | None = None) -> np.ndarray:
"""
Perform face segmentation using 5-point landmarks.
+ XSeg requires landmarks for face alignment. Unlike BiSeNet, calling
+ this method without landmarks will raise a :class:`ValueError`.
+
Args:
image (np.ndarray): Input image in BGR format.
- landmarks (np.ndarray): 5-point facial landmarks with shape (5, 2).
+ landmarks (np.ndarray | None): 5-point facial landmarks with shape (5, 2).
+ Required for XSeg face alignment.
Returns:
np.ndarray: Segmentation mask in original image space, values in [0, 1].
Raises:
- ValueError: If landmarks shape is not (5, 2).
+ ValueError: If landmarks is None or has incorrect shape.
"""
+ if landmarks is None:
+ raise ValueError(
+ 'XSeg requires 5-point facial landmarks for face alignment. Pass landmarks=... with shape (5, 2).'
+ )
if landmarks.shape != (5, 2):
raise ValueError(f'Landmarks must have shape (5, 2), got {landmarks.shape}')
diff --git a/uniface/privacy/__init__.py b/uniface/privacy/__init__.py
index b825beb..f555353 100644
--- a/uniface/privacy/__init__.py
+++ b/uniface/privacy/__init__.py
@@ -2,51 +2,6 @@
# Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo
-from __future__ import annotations
+from .blur import BlurFace, EllipticalBlur
-import numpy as np
-
-from .blur import BlurFace
-
-
-def anonymize_faces(
- image: np.ndarray,
- detector: object | None = None,
- method: str = 'pixelate',
- blur_strength: float = 3.0,
- pixel_blocks: int = 10,
- confidence_threshold: float = 0.5,
- **kwargs,
-) -> np.ndarray:
- """One-line face anonymization with automatic detection.
-
- Args:
- image (np.ndarray): Input image (BGR format).
- detector: Face detector instance. Creates RetinaFace if None.
- method (str): Blur method name. Defaults to 'pixelate'.
- blur_strength (float): Blur intensity. Defaults to 3.0.
- pixel_blocks (int): Block count for pixelate. Defaults to 10.
- confidence_threshold (float): Detection confidence threshold. Defaults to 0.5.
- **kwargs: Additional detector arguments.
-
- Returns:
- np.ndarray: Anonymized image.
-
- Example:
- >>> from uniface.privacy import anonymize_faces
- >>> anonymized = anonymize_faces(image, method='pixelate')
- """
- if detector is None:
- try:
- from uniface import RetinaFace
-
- detector = RetinaFace(confidence_threshold=confidence_threshold, **kwargs)
- except ImportError as err:
- raise ImportError('Could not import RetinaFace. Please ensure UniFace is properly installed.') from err
-
- faces = detector.detect(image)
- blurrer = BlurFace(method=method, blur_strength=blur_strength, pixel_blocks=pixel_blocks)
- return blurrer.anonymize(image, faces)
-
-
-__all__ = ['BlurFace', 'anonymize_faces']
+__all__ = ['BlurFace', 'EllipticalBlur']
diff --git a/uniface/spoofing/__init__.py b/uniface/spoofing/__init__.py
index 68a9fc4..625820d 100644
--- a/uniface/spoofing/__init__.py
+++ b/uniface/spoofing/__init__.py
@@ -4,6 +4,8 @@
from __future__ import annotations
+from typing import Any
+
from uniface.constants import MiniFASNetWeights
from uniface.types import SpoofingResult
@@ -22,6 +24,7 @@ __all__ = [
def create_spoofer(
model_name: MiniFASNetWeights = MiniFASNetWeights.V2,
scale: float | None = None,
+ **kwargs: Any,
) -> MiniFASNet:
"""Factory function to create a face anti-spoofing model.
@@ -34,6 +37,8 @@ def create_spoofer(
- MiniFASNetWeights.V1SE: Squeeze-and-excitation version, uses scale=4.0
scale: Custom crop scale factor for face region. If None, uses the
default scale for the selected model variant.
+ **kwargs: Additional keyword arguments forwarded to MiniFASNet
+ (e.g. ``providers=['CUDAExecutionProvider']``).
Returns:
An initialized face anti-spoofing model.
@@ -44,4 +49,4 @@ def create_spoofer(
>>> result = spoofer.predict(image, face.bbox)
>>> print(f'Is real: {result.is_real}, Confidence: {result.confidence:.2%}')
"""
- return MiniFASNet(model_name=model_name, scale=scale)
+ return MiniFASNet(model_name=model_name, scale=scale, **kwargs)
diff --git a/uniface/types.py b/uniface/types.py
index 9c48148..8fb61db 100644
--- a/uniface/types.py
+++ b/uniface/types.py
@@ -152,7 +152,7 @@ class Face:
race: Predicted race/ethnicity (optional, from FairFace).
emotion: Predicted emotion label (optional, from Emotion model).
emotion_confidence: Confidence score for emotion prediction (optional).
- track_id: Persistent track ID assigned by FaceTracker (optional).
+ track_id: Persistent track ID assigned by BYTETracker (optional).
Properties:
sex: Gender as a human-readable string ("Female" or "Male").