UniFace: A Unified Face Analysis Library for Python | Detection, alignment, landmarks, face-mesh, recognition, parsing, gaze, attributes and anti-spoofing under one API.
Python computer-visiondeep-learningface-alignmentface-analysisface-anonymizationface-anti-spoofingface-attributesface-detectionface-meshface-parsingface-quality-assessmentface-recognitionface-segmentationface-trackingfacial-landmarksgaze-estimationhead-pose-estimationonnxruntimeportrait-mattingpython
feat: Add face image quality assessment (#122)
Yakhyokhuja Valikhujaev446e3629fbf8
diff --git a/README.md b/README.mdindex 4410731..9e8b2cb 100644--- a/README.md+++ b/README.md@@ -36,6 +36,7 @@- **Attribute Analysis** — Age, gender, race (FairFace), and emotion- **Vector Store** — FAISS-backed embedding store for fast multi-identity search- **Anti-Spoofing** — Face liveness detection with MiniFASNet+- **Face Quality Assessment** — eDifFIQA single-score quality (T/S/M/L, NIST FATE-Quality #1 with the L variant)- **Face Anonymization** — 5 blur methods for privacy protection- **Hardware Acceleration** — ARM64 (Apple Silicon), CUDA (NVIDIA), CPU@@ -316,6 +317,7 @@ If you plan commercial use, verify model license compatibility.| Head Pose | [head-pose-estimation](https://github.com/yakhyo/head-pose-estimation) | ✓ | Head Pose Training (6DRepNet-style) || Matting | [modnet](https://github.com/yakhyo/modnet) | - | MODNet Portrait Matting || Anti-Spoofing | [face-anti-spoofing](https://github.com/yakhyo/face-anti-spoofing) | - | MiniFASNet Inference |+| Quality | [face-image-quality-assessment](https://github.com/yakhyo/face-image-quality-assessment) | - | eDifFIQA ONNX Inference || Attributes | [fairface-onnx](https://github.com/yakhyo/fairface-onnx) | - | FairFace ONNX Inference |*SCRFD and ArcFace models are from [InsightFace](https://github.com/deepinsight/insightface).diff --git a/docs/concepts/overview.md b/docs/concepts/overview.mdindex d67115b..2d0715c 100644--- a/docs/concepts/overview.md+++ b/docs/concepts/overview.md@@ -26,6 +26,7 @@ graph TBHPOSE[Head Pose]PARSE[Parsing]SPOOF[Anti-Spoofing]+ QUAL[Quality]MATT[Matting]PRIV[Privacy]end@@ -51,6 +52,7 @@ graph TBDET --> HPOSEDET --> PARSEDET --> SPOOF+ DET --> QUALDET --> PRIVDET --> TRKREC --> IDX@@ -120,7 +122,8 @@ uniface/├── matting/ # Portrait matting (MODNet)├── gaze/ # Gaze estimation├── headpose/ # Head pose estimation-├── spoofing/ # Anti-spoofing+├── spoofing/ # Anti-spoofing (MiniFASNet)+├── quality/ # Face image quality assessment (eDifFIQA)├── privacy/ # Face anonymization├── stores/ # Vector stores (FAISS)├── types.py # Dataclasses (Face, GazeResult, HeadPoseResult, etc.)diff --git a/docs/index.md b/docs/index.mdindex 454c3b4..04b3ad2 100644--- a/docs/index.md+++ b/docs/index.md@@ -13,17 +13,12 @@ template: home.html<p class="hero-subtitle">A Unified Face Analysis Library for Python</p>[](https://pypi.org/project/uniface/)-[](https://www.python.org/)+[](https://pepy.tech/projects/uniface)[](https://opensource.org/licenses/MIT)[](https://github.com/yakhyo/uniface/actions)-[](https://pepy.tech/projects/uniface)-[](https://www.kaggle.com/yakhyokhuja/code)-[](https://discord.gg/wdzrjr7R5j)--<!-- <img src="https://raw.githubusercontent.com/yakhyo/uniface/main/.github/logos/uniface_rounded_q80.webp" alt="UniFace - A Unified Face Analysis Library for Python" style="max-width: 70%; margin: 1rem 0;"> -->-[Get Started](quickstart.md){ .md-button .md-button--primary }-[View on GitHub](https://github.com/yakhyo/uniface){ .md-button }+[:material-rocket-launch: Get Started](quickstart.md){ .md-button .md-button--primary }+[:material-github: View on GitHub](https://github.com/yakhyo/uniface){ .md-button }</div>@@ -32,56 +27,73 @@ template: home.html<div class="feature-card" markdown>### :material-face-recognition: Face DetectionRetinaFace, SCRFD, and YOLO detectors with 5-point landmarks.+<a class="feature-card-link" href="modules/detection/" aria-label="Face Detection"></a></div><div class="feature-card" markdown>### :material-account-check: Face RecognitionAdaFace, ArcFace, EdgeFace, MobileFace, and SphereFace embeddings for identity verification.+<a class="feature-card-link" href="modules/recognition/" aria-label="Face Recognition"></a></div><div class="feature-card" markdown>### :material-map-marker: LandmarksDense facial landmark localization — 106-point (2d106det) and 98 / 68-point (PIPNet) variants.+<a class="feature-card-link" href="modules/landmarks/" aria-label="Landmarks"></a></div><div class="feature-card" markdown>### :material-account-details: AttributesAge, gender, race (FairFace), and emotion detection from faces.+<a class="feature-card-link" href="modules/attributes/" aria-label="Attributes"></a></div><div class="feature-card" markdown>### :material-face-man-shimmer: Face ParsingBiSeNet semantic segmentation with 19 facial component classes.+<a class="feature-card-link" href="modules/parsing/" aria-label="Face Parsing"></a></div><div class="feature-card" markdown>### :material-eye: Gaze EstimationReal-time gaze direction prediction with MobileGaze models.+<a class="feature-card-link" href="modules/gaze/" aria-label="Gaze Estimation"></a></div><div class="feature-card" markdown>### :material-axis-arrow: Head Pose3D head orientation (pitch, yaw, roll) estimation with 6D rotation models.+<a class="feature-card-link" href="modules/headpose/" aria-label="Head Pose"></a></div><div class="feature-card" markdown>### :material-motion-play: TrackingMulti-object tracking with BYTETracker for persistent face IDs across video frames.+<a class="feature-card-link" href="modules/tracking/" aria-label="Tracking"></a></div><div class="feature-card" markdown>### :material-shield-check: Anti-SpoofingFace liveness detection with MiniFASNet to prevent fraud.+<a class="feature-card-link" href="modules/spoofing/" aria-label="Anti-Spoofing"></a>+</div>++<div class="feature-card" markdown>+### :material-star-check: Face Quality+eDifFIQA scalar quality score to filter or rank faces before recognition.+<a class="feature-card-link" href="modules/quality/" aria-label="Face Quality"></a></div><div class="feature-card" markdown>### :material-blur: PrivacyFace anonymization with 5 blur methods for privacy protection.+<a class="feature-card-link" href="modules/privacy/" aria-label="Privacy"></a></div><div class="feature-card" markdown>### :material-database-search: Vector IndexingFAISS-backed embedding store for fast multi-identity face search.+<a class="feature-card-link" href="modules/stores/" aria-label="Vector Indexing"></a></div></div>@@ -118,29 +130,25 @@ pip install -e ".[cpu]" # or .[gpu] for CUDA<div class="feature-card" markdown>### :material-rocket-launch: QuickstartGet up and running in 5 minutes with common use cases.--[Quickstart Guide →](quickstart.md)+<a class="feature-card-link" href="quickstart/" aria-label="Quickstart"></a></div><div class="feature-card" markdown>### :material-school: TutorialsStep-by-step examples for common workflows.--[View Tutorials →](recipes/image-pipeline.md)+<a class="feature-card-link" href="recipes/image-pipeline/" aria-label="Tutorials"></a></div><div class="feature-card" markdown>### :material-api: API ReferenceExplore individual modules and their APIs.--[Browse API →](modules/detection.md)+<a class="feature-card-link" href="modules/detection/" aria-label="API Reference"></a></div><div class="feature-card" markdown>### :material-book-open-variant: GuidesLearn about the architecture and design principles.--[Read Guides →](concepts/overview.md)+<a class="feature-card-link" href="concepts/overview/" aria-label="Guides"></a></div></div>diff --git a/docs/models.md b/docs/models.mdindex b79aed5..471eac1 100644--- a/docs/models.md+++ b/docs/models.md@@ -440,6 +440,27 @@ Face anti-spoofing models for liveness detection. Detect if a face is real (live---+## Face Image Quality Models++### eDifFIQA Family++Face image quality assessment. Predicts a single scalar score from an aligned 112x112 face crop — higher = better. eDifFIQA-L ranks first on the NIST FATE-Quality Kiosk-to-Entry track.++| Model Name | Backbone | Params | Size |+| ---------- | -------- | ------ | ---- |+| `T` :material-check-circle: | MobileFaceNet | 1.7M | 6.6 MB |+| `S` | IResNet-18 | 24.6M | 93.7 MB |+| `M` | IResNet-50 | 44.1M | 168.3 MB |+| `L` | IResNet-100 | 65.7M | 250.6 MB |++!!! info "Output Format"+ **Output**: Returns `QualityResult(score)` — float, roughly in `[0, 1]`. Not a calibrated probability; calibrate your threshold on a held-out set.++!!! note "Input Requirements"+ Requires 5-point landmarks from a detector (e.g. SCRFD, RetinaFace) for alignment, or a pre-aligned 112x112 crop via `score_aligned()`.++---+## Model ManagementModels are automatically downloaded and cached on first use.@@ -472,6 +493,7 @@ See [Model Cache & Offline Use](concepts/model-cache-offline.md) for full detail- **Face Segmentation**: [yakhyo/face-segmentation](https://github.com/yakhyo/face-segmentation) - XSeg ONNX Inference- **Portrait Matting**: [yakhyo/modnet](https://github.com/yakhyo/modnet) - MODNet ported weights and inference (from [ZHKKKe/MODNet](https://github.com/ZHKKKe/MODNet))- **Face Anti-Spoofing**: [yakhyo/face-anti-spoofing](https://github.com/yakhyo/face-anti-spoofing) - MiniFASNet ONNX inference (weights from [minivision-ai/Silent-Face-Anti-Spoofing](https://github.com/minivision-ai/Silent-Face-Anti-Spoofing))+- **Face Image Quality Assessment**: [yakhyo/face-image-quality-assessment](https://github.com/yakhyo/face-image-quality-assessment) - eDifFIQA PyTorch inference, ONNX export and inference- **FairFace**: [yakhyo/fairface-onnx](https://github.com/yakhyo/fairface-onnx) - FairFace ONNX inference for race, gender, age prediction- **PIPNet**: [yakhyo/pipnet-onnx](https://github.com/yakhyo/pipnet-onnx) - PIPNet ONNX export and inference (from [jhb86253817/PIPNet](https://github.com/jhb86253817/PIPNet))- **InsightFace**: [deepinsight/insightface](https://github.com/deepinsight/insightface) - Model architectures and pretrained weightsdiff --git a/docs/modules/attributes.md b/docs/modules/attributes.mdindex e4afb20..9920c27 100644--- a/docs/modules/attributes.md+++ b/docs/modules/attributes.md@@ -300,3 +300,4 @@ cv2.imwrite("attributes.jpg", image)- [Parsing](parsing.md) - Face semantic segmentation- [Gaze](gaze.md) - Gaze estimation- [Image Pipeline Recipe](../recipes/image-pipeline.md) - Complete workflow+- [CLI Tools](https://github.com/yakhyo/uniface/blob/main/tools/README.md) - Command-line scripts for all UniFace modulesdiff --git a/docs/modules/detection.md b/docs/modules/detection.mdindex c476aaa..935141c 100644--- a/docs/modules/detection.md+++ b/docs/modules/detection.md@@ -294,3 +294,4 @@ python tools/detect.py --source image.jpg- [Landmarks Module](landmarks.md) - Get 106 / 98 / 68-point dense landmarks- [Image Pipeline Recipe](../recipes/image-pipeline.md) - Complete detection workflow- [Concepts: Thresholds](../concepts/thresholds-calibration.md) - Tuning detection parameters+- [CLI Tools](https://github.com/yakhyo/uniface/blob/main/tools/README.md) - Command-line scripts for all UniFace modulesdiff --git a/docs/modules/gaze.md b/docs/modules/gaze.mdindex 9fb16b6..2f3811c 100644--- a/docs/modules/gaze.md+++ b/docs/modules/gaze.md@@ -276,3 +276,4 @@ gaze = MobileGaze()- [Anti-Spoofing](spoofing.md) - Face liveness detection- [Privacy](privacy.md) - Face anonymization- [Video Recipe](../recipes/video-webcam.md) - Real-time processing+- [CLI Tools](https://github.com/yakhyo/uniface/blob/main/tools/README.md) - Command-line scripts for all UniFace modulesdiff --git a/docs/modules/headpose.md b/docs/modules/headpose.mdindex 2ff5e46..53f4145 100644--- a/docs/modules/headpose.md+++ b/docs/modules/headpose.md@@ -235,3 +235,4 @@ hp = HeadPose()- [Gaze Estimation](gaze.md) - Eye gaze direction- [Anti-Spoofing](spoofing.md) - Face liveness detection- [Video Recipe](../recipes/video-webcam.md) - Real-time processing+- [CLI Tools](https://github.com/yakhyo/uniface/blob/main/tools/README.md) - Command-line scripts for all UniFace modulesdiff --git a/docs/modules/landmarks.md b/docs/modules/landmarks.mdindex a0ecc9f..3e60142 100644--- a/docs/modules/landmarks.md+++ b/docs/modules/landmarks.md@@ -307,3 +307,4 @@ landmarker = PIPNet(model_name=PIPNetWeights.DW300_CELEBA_68)- [Attributes Module](attributes.md) - Age, gender, emotion- [Gaze Module](gaze.md) - Gaze estimation- [Concepts: Coordinate Systems](../concepts/coordinate-systems.md) - Landmark formats+- [CLI Tools](https://github.com/yakhyo/uniface/blob/main/tools/README.md) - Command-line scripts for all UniFace modulesdiff --git a/docs/modules/matting.md b/docs/modules/matting.mdindex 7bd6909..15af3b3 100644--- a/docs/modules/matting.md+++ b/docs/modules/matting.md@@ -152,3 +152,4 @@ matting = MODNet(model_name=MODNetWeights.WEBCAM)- [Parsing](parsing.md) - Face semantic segmentation- [Privacy](privacy.md) - Face anonymization- [Detection](detection.md) - Face detection+- [CLI Tools](https://github.com/yakhyo/uniface/blob/main/tools/README.md) - Command-line scripts for all UniFace modulesdiff --git a/docs/modules/parsing.md b/docs/modules/parsing.mdindex 3848a46..37eecde 100644--- a/docs/modules/parsing.md+++ b/docs/modules/parsing.md@@ -337,3 +337,4 @@ parser = XSeg(model_name=XSegWeights.DEFAULT)- [Gaze](gaze.md) - Gaze estimation- [Privacy](privacy.md) - Face anonymization- [Detection](detection.md) - Face detection+- [CLI Tools](https://github.com/yakhyo/uniface/blob/main/tools/README.md) - Command-line scripts for all UniFace modulesdiff --git a/docs/modules/privacy.md b/docs/modules/privacy.mdindex 4e73502..8f50a7b 100644--- a/docs/modules/privacy.md+++ b/docs/modules/privacy.md@@ -243,23 +243,9 @@ for method in methods:----## Command-Line Tool--```bash-# Anonymize image with pixelation-python tools/anonymize.py --source photo.jpg--# Real-time webcam-python tools/anonymize.py --source 0 --method gaussian--# Custom blur strength-python tools/anonymize.py --source photo.jpg --method gaussian --blur-strength 5.0-```------## Next Steps- [Anonymize Stream Recipe](../recipes/anonymize-stream.md) - Video pipeline- [Detection](detection.md) - Face detection options- [Batch Processing Recipe](../recipes/batch-processing.md) - Process multiple files+- [CLI Tools](https://github.com/yakhyo/uniface/blob/main/tools/README.md) - Command-line scripts for all UniFace modulesdiff --git a/docs/modules/quality.md b/docs/modules/quality.mdnew file mode 100644index 0000000..eaae2d6--- /dev/null+++ b/docs/modules/quality.md@@ -0,0 +1,204 @@+# Face Image Quality Assessment++Face image quality assessment predicts a single scalar score from an aligned face crop. Higher score = better quality (sharpness, frontalness, illumination, low occlusion). Use the score to filter or rank faces before recognition.++UniFace ships [eDifFIQA](https://github.com/yakhyo/face-image-quality-assessment), which ranks first on the NIST [FATE-Quality](https://pages.nist.gov/frvt/html/frvt_quality.html) Kiosk-to-Entry track with the L variant.++---++## Available Models++| Variant | Backbone | Params | Size |+|---------|----------|--------|------|+| **eDifFIQA-T** :material-check-circle: | MobileFaceNet | 1.7M | 6.6 MB |+| eDifFIQA-S | IResNet-18 | 24.6M | 93.7 MB |+| eDifFIQA-M | IResNet-50 | 44.1M | 168.3 MB |+| eDifFIQA-L | IResNet-100 | 65.7M | 250.6 MB |++All variants take an aligned 112x112 face crop and output a scalar score in roughly [0, 1].++---++## Basic Usage++```python+import cv2+from uniface.detection import SCRFD+from uniface.quality import EDifFIQA++# Lower SCRFD's confidence threshold so quality scoring sees every plausible+# face — including the low-confidence ones that quality scoring is meant to flag.+detector = SCRFD(confidence_threshold=0.3)+quality = EDifFIQA()++image = cv2.imread("photo.jpg")+faces = detector.detect(image)++for face in faces:+ result = quality.predict(image, face.landmarks)+ print(f"Quality: {result.score:.4f}")+```++`predict` aligns the face using the 5-point landmarks and runs inference. To skip alignment (pre-aligned 112x112 crop), call `score_aligned` instead:++```python+result = quality.score_aligned(aligned_face)+```++!!! tip "Detector threshold"+ SCRFD's default `confidence_threshold` is 0.5, which can miss tightly-cropped or partial faces — exactly the cases you want quality scoring to surface. Drop it to ~0.3 for quality use cases.++---++## Output Format++```python+result = quality.predict(image, face.landmarks)++# QualityResult dataclass+result.score # float, higher = better+```++Scores are roughly in `[0, 1]` but eDifFIQA is **not** a calibrated probability — the absolute number is only meaningful relative to other faces from the same model. As a rough guide from the upstream demo (eDifFIQA-T):++| Score | Typical face |+|-------|--------------|+| ≥ 0.7 | Sharp, frontal, well-lit |+| 0.4 – 0.7 | Acceptable (some blur / off-angle / low-res) |+| < 0.3 | Heavy blur, occlusion, or severe degradation |++Calibrate your own threshold on a held-out set rather than reusing these bands verbatim.++---++## Model Variants++```python+from uniface.quality import EDifFIQA+from uniface.constants import EDifFIQAWeights++# Default (T, smallest, recommended for real-time)+quality = EDifFIQA()++# More accurate variants+quality = EDifFIQA(model_name=EDifFIQAWeights.S)+quality = EDifFIQA(model_name=EDifFIQAWeights.M)+quality = EDifFIQA(model_name=EDifFIQAWeights.L)+```++---++## Visualization++```python+from uniface.draw import draw_quality_score++for face in faces:+ result = quality.predict(image, face.landmarks)+ draw_quality_score(image, face.bbox, result.score)++cv2.imwrite("quality_output.jpg", image)+```++The label is color-coded by score: red (< 0.3), orange (0.3-0.6), green (>= 0.6). Adjust with `low_threshold` and `high_threshold` kwargs.++---++## Use Cases++### Filter Low-Quality Faces Before Recognition++```python+from uniface.detection import SCRFD+from uniface.quality import EDifFIQA+from uniface.recognition import ArcFace++detector = SCRFD(confidence_threshold=0.3)+quality = EDifFIQA()+recognizer = ArcFace()++MIN_QUALITY = 0.5 # tune on your data++for face in detector.detect(image):+ score = quality.predict(image, face.landmarks).score+ if score < MIN_QUALITY:+ continue+ face.embedding = recognizer.get_normalized_embedding(image, face.landmarks)+```++### Rank Faces in a Video++```python+best = (None, -1.0) # (frame_idx, score)++for idx, frame in enumerate(frames):+ for face in detector.detect(frame):+ score = quality.predict(frame, face.landmarks).score+ if score > best[1]:+ best = (idx, score)++print(f"Best frame: {best[0]} (quality {best[1]:.4f})")+```++### Best-of-N Enrollment++Pick the sharpest frame from a short capture for face enrollment:++```python+def best_face_from_capture(frames, detector, quality):+ """Return the (frame, face) with the highest quality across frames."""+ best = (None, None, -1.0)+ for frame in frames:+ for face in detector.detect(frame):+ score = quality.predict(frame, face.landmarks).score+ if score > best[2]:+ best = (frame, face, score)+ return best # (frame, face, score)+```++---++## Real-Time Webcam++```python+import cv2+from uniface.detection import SCRFD+from uniface.quality import EDifFIQA+from uniface.draw import draw_quality_score++detector = SCRFD(confidence_threshold=0.3)+quality = EDifFIQA()++cap = cv2.VideoCapture(0)+while True:+ ret, frame = cap.read()+ if not ret:+ break++ for face in detector.detect(frame):+ result = quality.predict(frame, face.landmarks)+ draw_quality_score(frame, face.bbox, result.score)++ cv2.imshow("Face Quality", frame)+ if cv2.waitKey(1) & 0xFF == ord('q'):+ break++cap.release()+cv2.destroyAllWindows()+```++---++## Reference++- Paper: ["eDifFIQA: Towards Efficient Face Image Quality Assessment based on Denoising Diffusion Probabilistic Models"](https://ieeexplore.ieee.org/document/10468647) (Babnik et al., IEEE T-BIOM 2024)+- Code: [yakhyo/face-image-quality-assessment](https://github.com/yakhyo/face-image-quality-assessment) — PyTorch inference, ONNX export, and ONNX Runtime inference. ONNX weights for UniFace are mirrored here.++---++## Next Steps++- [Recognition](recognition.md) - Run recognition only on high-quality faces+- [Anti-Spoofing](spoofing.md) - Liveness check+- [Detection](detection.md) - Face detection+- [CLI Tools](https://github.com/yakhyo/uniface/blob/main/tools/README.md) - Command-line scripts for all UniFace modulesdiff --git a/docs/modules/recognition.md b/docs/modules/recognition.mdindex 02ef19f..8cbccda 100644--- a/docs/modules/recognition.md+++ b/docs/modules/recognition.md@@ -365,3 +365,4 @@ recognizer = EdgeFace()- [Detection Module](detection.md) - Detect faces first- [Face Search Recipe](../recipes/face-search.md) - Complete search system- [Thresholds](../concepts/thresholds-calibration.md) - Calibration guide+- [CLI Tools](https://github.com/yakhyo/uniface/blob/main/tools/README.md) - Command-line scripts for all UniFace modulesdiff --git a/docs/modules/spoofing.md b/docs/modules/spoofing.mdindex 87624d4..c50bd1e 100644--- a/docs/modules/spoofing.md+++ b/docs/modules/spoofing.md@@ -238,18 +238,6 @@ MiniFASNet can detect various spoof attacks:----## Command-Line Tool--```bash-# Image-python tools/spoofing.py --source photo.jpg--# Webcam-python tools/spoofing.py --source 0-```------## Available Spoofers```python@@ -265,3 +253,4 @@ spoofer = MiniFASNet()- [Privacy](privacy.md) - Face anonymization- [Detection](detection.md) - Face detection- [Recognition](recognition.md) - Face recognition+- [CLI Tools](https://github.com/yakhyo/uniface/blob/main/tools/README.md) - Command-line scripts for all UniFace modulesdiff --git a/docs/modules/stores.md b/docs/modules/stores.mdindex d2ddbdd..0613c2f 100644--- a/docs/modules/stores.md+++ b/docs/modules/stores.md@@ -170,3 +170,4 @@ else:- [Face Search Recipe](../recipes/face-search.md) - Building and querying indexes- [Recognition Module](recognition.md) - Embedding extraction- [Thresholds Guide](../concepts/thresholds-calibration.md) - Tuning similarity thresholds+- [CLI Tools](https://github.com/yakhyo/uniface/blob/main/tools/README.md) - Command-line scripts for all UniFace modulesdiff --git a/docs/modules/tracking.md b/docs/modules/tracking.mdindex ca7cae6..69bfd8f 100644--- a/docs/modules/tracking.md+++ b/docs/modules/tracking.md@@ -228,27 +228,6 @@ draw_tracks(----## CLI Tool--```bash-# Track faces in a video-python tools/track.py --source video.mp4--# Webcam-python tools/track.py --source 0--# Save output-python tools/track.py --source video.mp4 --output tracked.mp4--# Use RetinaFace instead of SCRFD-python tools/track.py --source video.mp4 --detector retinaface--# Keep lost tracks longer-python tools/track.py --source video.mp4 --track-buffer 60-```------## References- [yakhyo/bytetrack-tracker](https://github.com/yakhyo/bytetrack-tracker) — standalone BYTETracker implementation used in UniFace@@ -261,3 +240,4 @@ python tools/track.py --source video.mp4 --track-buffer 60- [Detection](detection.md) — face detection models- [Video & Webcam](../recipes/video-webcam.md) — video processing patterns- [Inputs & Outputs](../concepts/inputs-outputs.md) — data types and formats+- [CLI Tools](https://github.com/yakhyo/uniface/blob/main/tools/README.md) — command-line scripts for all UniFace modulesdiff --git a/docs/quickstart.md b/docs/quickstart.mdindex ce586d4..ae6cf7b 100644--- a/docs/quickstart.md+++ b/docs/quickstart.md@@ -384,6 +384,30 @@ for i, face in enumerate(faces):---+## Face Image Quality Assessment++Score how usable each face is for downstream recognition:++```python+import cv2+from uniface.detection import SCRFD+from uniface.quality import EDifFIQA++detector = SCRFD(confidence_threshold=0.3)+quality = EDifFIQA()++image = cv2.imread("photo.jpg")+faces = detector.detect(image)++for i, face in enumerate(faces):+ result = quality.predict(image, face.landmarks)+ print(f"Face {i+1}: quality={result.score:.4f}")+```++Higher = better. Use it to filter or rank faces before recognition.++---+## Webcam DemoReal-time face detection:@@ -489,6 +513,7 @@ For detailed model comparisons and benchmarks, see the [Model Zoo](models.md).| Parsing | `BiSeNet` (ResNet18/34) || Attributes | `AgeGender`, `FairFace`, `Emotion` || Anti-Spoofing | `MiniFASNet` (V1SE, V2) |+| Quality | `EDifFIQA` (T, S, M, L) |---@@ -535,6 +560,7 @@ from uniface.gaze import MobileGazefrom uniface.headpose import HeadPosefrom uniface.parsing import BiSeNet, XSegfrom uniface.privacy import BlurFace+from uniface.quality import EDifFIQAfrom uniface.spoofing import MiniFASNetfrom uniface.tracking import BYTETrackerfrom uniface.analyzer import FaceAnalyzerdiff --git a/docs/stylesheets/extra.css b/docs/stylesheets/extra.cssindex fd8b225..79914d7 100644--- a/docs/stylesheets/extra.css+++ b/docs/stylesheets/extra.css@@ -1,5 +1,45 @@/* UniFace Documentation - Custom Styles */+/* ===== Announcement Bar ===== */++/* Light theme: indigo gradient, white text. */+[data-md-color-scheme="default"] .md-banner {+ background: linear-gradient(90deg, #3f51b5 0%, #7c4dff 100%);+ color: #ffffff;+}++[data-md-color-scheme="default"] .md-banner a {+ color: #ffffff;+ text-decoration: none;+}++[data-md-color-scheme="default"] .md-banner a:hover {+ text-decoration: underline;+}++[data-md-color-scheme="default"] .md-banner .twemoji svg {+ fill: #ffd54f;+}++/* Dark theme: deeper purple gradient, soft gold star. */+[data-md-color-scheme="slate"] .md-banner {+ background: linear-gradient(90deg, #4527a0 0%, #7c4dff 100%);+ color: #ffffff;+}++[data-md-color-scheme="slate"] .md-banner a {+ color: #ffffff;+ text-decoration: none;+}++[data-md-color-scheme="slate"] .md-banner a:hover {+ text-decoration: underline;+}++[data-md-color-scheme="slate"] .md-banner .twemoji svg {+ fill: #ffd54f;+}+/* ===== Hero Section ===== */.md-content .hero {@@ -36,34 +76,45 @@.hero .md-button {margin: 0.5rem 0.25rem;- padding: 0.7rem 1.5rem;- font-weight: 600;- border-radius: 8px;- transition: all 0.2s ease;+ padding: 0.6rem 1.25rem;+ font-weight: 500;+ font-size: 0.9rem;+ border-radius: 6px;+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+ transition: background-color 0.15s ease, border-color 0.15s ease, color 0.15s ease;+}++.hero .md-button .twemoji,+.hero .md-button svg {+ width: 1em;+ height: 1em;+ fill: currentColor;}.hero .md-button--primary {- background: linear-gradient(135deg, var(--md-primary-fg-color) 0%, #5c6bc0 100%);- border: none;- box-shadow: 0 4px 14px rgba(63, 81, 181, 0.4);+ background: var(--md-primary-fg-color);+ border: 1px solid var(--md-primary-fg-color);+ color: #ffffff;}.hero .md-button--primary:hover {- transform: translateY(-2px);- box-shadow: 0 6px 20px rgba(63, 81, 181, 0.5);+ background: var(--md-primary-fg-color--dark, #303f9f);+ border-color: var(--md-primary-fg-color--dark, #303f9f);+ color: #ffffff;}.hero .md-button:not(.md-button--primary) {- border: 2px solid var(--md-primary-fg-color);background: transparent;- color: var(--md-primary-fg-color);+ border: 1px solid var(--md-default-fg-color--lighter);+ color: var(--md-default-fg-color);}.hero .md-button:not(.md-button--primary):hover {- background: var(--md-primary-fg-color);- border-color: var(--md-primary-fg-color);- color: white;- transform: translateY(-2px);+ background: var(--md-default-fg-color--lightest);+ border-color: var(--md-default-fg-color--light);+ color: var(--md-default-fg-color);}/* Badge styling in hero */@@ -85,31 +136,21 @@border-radius: 12px;background: var(--md-code-bg-color);border: 1px solid var(--md-default-fg-color--lightest);- transition: all 0.3s ease;position: relative;- overflow: hidden;-}--.feature-card::before {- content: '';- position: absolute;- top: 0;- left: 0;- right: 0;- height: 3px;- background: linear-gradient(90deg, var(--md-primary-fg-color), #7c4dff);- opacity: 0;- transition: opacity 0.3s ease;+ transition: border-color 0.2s ease;}.feature-card:hover {- transform: translateY(-4px);- box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);- border-color: var(--md-primary-fg-color--light);+ border-color: var(--md-accent-fg-color);}-.feature-card:hover::before {- opacity: 1;+/* Transparent overlay link — makes the whole card clickable. */+.feature-card-link {+ position: absolute;+ inset: 0;+ z-index: 1;+ border-radius: inherit;+ text-decoration: none;}.feature-card h3 {@@ -129,13 +170,6 @@line-height: 1.5;}-.feature-card a {- display: inline-block;- margin-top: 0.75rem;- font-weight: 500;- font-size: 0.875rem;-}-/* ===== Next Steps Grid (2 columns) ===== */.next-steps-grid {display: grid;@@ -160,30 +194,28 @@background-clip: text;}-[data-md-color-scheme="slate"] .feature-card:hover {- box-shadow: 0 12px 24px rgba(0, 0, 0, 0.3);-}-[data-md-color-scheme="slate"] .hero .md-button--primary {- background: linear-gradient(135deg, #7c4dff 0%, #b388ff 100%);- box-shadow: 0 4px 14px rgba(124, 77, 255, 0.4);+ background: #ffffff;+ border-color: #ffffff;+ color: #1a1a2e;}[data-md-color-scheme="slate"] .hero .md-button--primary:hover {- box-shadow: 0 6px 20px rgba(124, 77, 255, 0.5);+ background: #e6e6e6;+ border-color: #e6e6e6;+ color: #1a1a2e;}[data-md-color-scheme="slate"] .hero .md-button:not(.md-button--primary) {- border: 2px solid rgba(255, 255, 255, 0.3);- background: rgba(255, 255, 255, 0.05);+ background: transparent;+ border: 1px solid rgba(255, 255, 255, 0.25);color: rgba(255, 255, 255, 0.9);}[data-md-color-scheme="slate"] .hero .md-button:not(.md-button--primary):hover {- background: rgba(255, 255, 255, 0.1);- border-color: rgba(255, 255, 255, 0.5);- color: white;- transform: translateY(-2px);+ background: rgba(255, 255, 255, 0.08);+ border-color: rgba(255, 255, 255, 0.4);+ color: #ffffff;}/* ===== Responsive Design ===== */diff --git a/mkdocs.yml b/mkdocs.ymlindex eaa6c4e..426a966 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -154,6 +154,7 @@ nav:- Gaze: modules/gaze.md- Head Pose: modules/headpose.md- Anti-Spoofing: modules/spoofing.md+ - Quality: modules/quality.md- Privacy: modules/privacy.md- Stores: modules/stores.md- Guides:diff --git a/tests/test_quality.py b/tests/test_quality.pynew file mode 100644index 0000000..afcbcd3--- /dev/null+++ b/tests/test_quality.py@@ -0,0 +1,107 @@+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo+++from __future__ import annotations++import numpy as np+import pytest++from uniface import EDifFIQA, QualityResult+from uniface.constants import EDifFIQAWeights+++def test_ediffiqa_initialization():+ """Test EDifFIQA initialization with default weights (T)."""+ estimator = EDifFIQA()+ assert estimator is not None+ assert estimator.input_size == (112, 112)+++def test_ediffiqa_with_explicit_variant():+ """Test EDifFIQA initialization with explicit T variant."""+ estimator = EDifFIQA(model_name=EDifFIQAWeights.T)+ assert estimator is not None+ assert estimator.input_size == (112, 112)+++def test_ediffiqa_with_providers():+ """Test that EDifFIQA accepts providers kwarg."""+ estimator = EDifFIQA(providers=['CPUExecutionProvider'])+ assert isinstance(estimator, EDifFIQA)+++def test_ediffiqa_preprocess_shape():+ """Test preprocessing produces correct tensor shape and dtype."""+ estimator = EDifFIQA()+ aligned = np.random.randint(0, 255, (112, 112, 3), dtype=np.uint8)+ blob = estimator.preprocess(aligned)++ assert blob.dtype == np.float32+ assert blob.shape == (1, 3, 112, 112)+++def test_ediffiqa_score_aligned_returns_quality_result():+ """Test scoring a pre-aligned crop returns a QualityResult."""+ estimator = EDifFIQA()+ aligned = np.random.randint(0, 255, (112, 112, 3), dtype=np.uint8)+ result = estimator.score_aligned(aligned)++ assert isinstance(result, QualityResult)+ assert isinstance(result.score, float)+++def test_ediffiqa_predict_with_landmarks():+ """Test end-to-end prediction from full image + landmarks."""+ estimator = EDifFIQA()+ image = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)+ # 5-point landmarks roughly centered in the image+ landmarks = np.array(+ [+ [260.0, 220.0],+ [380.0, 220.0],+ [320.0, 280.0],+ [275.0, 340.0],+ [365.0, 340.0],+ ],+ dtype=np.float32,+ )+ result = estimator.predict(image, landmarks)++ assert isinstance(result, QualityResult)+ assert isinstance(result.score, float)+++def test_ediffiqa_callable():+ """Test that EDifFIQA is callable via __call__."""+ estimator = EDifFIQA()+ image = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)+ landmarks = np.array(+ [+ [260.0, 220.0],+ [380.0, 220.0],+ [320.0, 280.0],+ [275.0, 340.0],+ [365.0, 340.0],+ ],+ dtype=np.float32,+ )+ result = estimator(image, landmarks)++ assert isinstance(result, QualityResult)+++def test_quality_result_repr():+ """Test QualityResult repr formatting."""+ result = QualityResult(score=0.7620)+ repr_str = repr(result)+ assert 'QualityResult' in repr_str+ assert '0.7620' in repr_str+++def test_quality_result_frozen():+ """Test that QualityResult is immutable."""+ result = QualityResult(score=0.5)+ with pytest.raises(AttributeError):+ result.score = 0.9 # type: ignore[misc]diff --git a/tools/README.md b/tools/README.mdindex e0ae7f9..b4e5107 100644--- a/tools/README.md+++ b/tools/README.md@@ -20,6 +20,7 @@ CLI utilities for testing and running UniFace features.| `fairface.py` | FairFace attribute prediction (race, gender, age) || `attribute.py` | Age and gender prediction || `spoofing.py` | Face anti-spoofing detection |+| `quality.py` | Face image quality assessment (eDifFIQA) || `parse.py` | Face semantic segmentation (BiSeNet) || `xseg.py` | Face segmentation (XSeg) || `batch_process.py` | Batch process folder of images |@@ -88,6 +89,11 @@ python tools/xseg.py --source 0python tools/spoofing.py --source assets/test.jpgpython tools/spoofing.py --source 0+# Face image quality assessment (eDifFIQA)+python tools/quality.py --source assets/test.jpg+python tools/quality.py --source 0+python tools/quality.py --source assets/test.jpg --variant l+# Face analyzerpython tools/analyze.py --source assets/test.jpgpython tools/analyze.py --source 0diff --git a/tools/quality.py b/tools/quality.pynew file mode 100644index 0000000..9527840--- /dev/null+++ b/tools/quality.py@@ -0,0 +1,179 @@+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo++"""Face Image Quality Assessment.++Usage:+ python tools/quality.py --source path/to/image.jpg+ python tools/quality.py --source path/to/video.mp4+ python tools/quality.py --source 0 # webcam+"""++from __future__ import annotations++import argparse+import os+from pathlib import Path++from _common import get_source_type+import cv2++from uniface.constants import EDifFIQAWeights+from uniface.detection import SCRFD+from uniface.draw import draw_quality_score+from uniface.quality import EDifFIQA++VARIANT_MAP = {+ 't': EDifFIQAWeights.T,+ 's': EDifFIQAWeights.S,+ 'm': EDifFIQAWeights.M,+ 'l': EDifFIQAWeights.L,+}+++def process_image(detector, quality, image_path: str, save_dir: str = 'outputs') -> None:+ """Score every detected face in an image and save an annotated copy."""+ image = cv2.imread(image_path)+ if image is None:+ print(f"Error: Failed to load image from '{image_path}'")+ return++ faces = detector.detect(image)+ print(f'Detected {len(faces)} face(s)')++ if not faces:+ print('No faces detected in the image.')+ return++ for i, face in enumerate(faces, 1):+ result = quality.predict(image, face.landmarks)+ print(f' Face {i}: quality={result.score:.4f}')+ draw_quality_score(image, face.bbox, result.score)++ os.makedirs(save_dir, exist_ok=True)+ output_path = os.path.join(save_dir, f'{Path(image_path).stem}_quality.jpg')+ cv2.imwrite(output_path, image)+ print(f'Output saved: {output_path}')+++def process_video(detector, quality, video_path: str, save_dir: str = 'outputs') -> None:+ """Score faces frame-by-frame in a video and save an annotated copy."""+ cap = cv2.VideoCapture(video_path)+ if not cap.isOpened():+ print(f"Error: Cannot open video file '{video_path}'")+ return++ fps = cap.get(cv2.CAP_PROP_FPS)+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))++ os.makedirs(save_dir, exist_ok=True)+ output_path = os.path.join(save_dir, f'{Path(video_path).stem}_quality.mp4')+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')+ out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))++ print(f'Processing video: {video_path} ({total_frames} frames)')+ frame_count = 0++ while True:+ ret, frame = cap.read()+ if not ret:+ break++ frame_count += 1+ faces = detector.detect(frame)++ for face in faces:+ result = quality.predict(frame, face.landmarks)+ draw_quality_score(frame, face.bbox, result.score)++ out.write(frame)++ if frame_count % 100 == 0:+ print(f' Processed {frame_count}/{total_frames} frames...')++ cap.release()+ out.release()+ print(f'Done! Output saved: {output_path}')+++def run_camera(detector, quality, camera_id: int = 0) -> None:+ """Run real-time quality assessment on webcam."""+ cap = cv2.VideoCapture(camera_id)+ if not cap.isOpened():+ print(f'Cannot open camera {camera_id}')+ return++ print("Press 'q' to quit")++ while True:+ ret, frame = cap.read()+ if not ret:+ break++ frame = cv2.flip(frame, 1)+ faces = detector.detect(frame)++ for face in faces:+ result = quality.predict(frame, face.landmarks)+ draw_quality_score(frame, face.bbox, result.score)++ cv2.imshow('Face Quality Assessment', frame)+ if cv2.waitKey(1) & 0xFF == ord('q'):+ break++ cap.release()+ cv2.destroyAllWindows()+++def main():+ parser = argparse.ArgumentParser(description='Face Image Quality Assessment (eDifFIQA)')+ parser.add_argument('--source', type=str, required=True, help='Image/video path or camera ID (0, 1, ...)')+ parser.add_argument(+ '--variant',+ type=str,+ default='t',+ choices=['t', 's', 'm', 'l'],+ help='eDifFIQA model variant (default: t)',+ )+ parser.add_argument('--save-dir', type=str, default='outputs', help='Output directory')+ parser.add_argument(+ '--detector-conf',+ type=float,+ default=0.3,+ help='SCRFD confidence threshold (default: 0.3, lower than the SCRFD default of 0.5)',+ )+ args = parser.parse_args()++ model_name = VARIANT_MAP[args.variant]++ print(f'Initializing models (SCRFD + eDifFIQA-{args.variant.upper()})...')+ # Lower the default SCRFD threshold (0.5 -> 0.3): quality scoring wants+ # to see every plausible face, including the low-confidence ones that+ # are precisely what the quality model is meant to flag.+ detector = SCRFD(confidence_threshold=args.detector_conf)+ quality = EDifFIQA(model_name=model_name)++ source_type = get_source_type(args.source)++ if source_type == 'camera':+ run_camera(detector, quality, int(args.source))+ elif source_type == 'image':+ if not os.path.exists(args.source):+ print(f'Error: Image not found: {args.source}')+ return+ process_image(detector, quality, args.source, args.save_dir)+ elif source_type == 'video':+ if not os.path.exists(args.source):+ print(f'Error: Video not found: {args.source}')+ return+ process_video(detector, quality, args.source, args.save_dir)+ else:+ print(f"Error: Unknown source type for '{args.source}'")+ print('Supported formats: images (.jpg, .png, ...), videos (.mp4, .avi, ...), or camera ID (0, 1, ...)')+++if __name__ == '__main__':+ main()diff --git a/uniface/__init__.py b/uniface/__init__.pyindex 3b320f2..d7dcec2 100644--- a/uniface/__init__.py+++ b/uniface/__init__.py@@ -24,6 +24,7 @@ This library provides unified APIs for:- Head pose estimation- Age, gender, and emotion prediction- Face anti-spoofing+- Face image quality assessment (eDifFIQA)- Privacy/anonymization"""@@ -55,10 +56,11 @@ from .landmark import Landmark106, PIPNet, create_landmarkerfrom .matting import MODNet, create_matting_modelfrom .parsing import BiSeNet, XSeg, create_face_parserfrom .privacy import BlurFace+from .quality import EDifFIQAfrom .recognition import AdaFace, ArcFace, EdgeFace, MobileFace, SphereFace, create_recognizerfrom .spoofing import MiniFASNet, create_spooferfrom .tracking import BYTETracker-from .types import AttributeResult, EmotionResult, Face, GazeResult, HeadPoseResult, SpoofingResult+from .types import AttributeResult, EmotionResult, Face, GazeResult, HeadPoseResult, QualityResult, SpoofingResult# Optional: FAISS vector store (requires `pip install faiss-cpu`)with contextlib.suppress(ImportError):@@ -117,6 +119,9 @@ __all__ = [# Spoofing models'MiniFASNet','SpoofingResult',+ # Quality models+ 'EDifFIQA',+ 'QualityResult',# Tracking'BYTETracker',# Privacydiff --git a/uniface/constants.py b/uniface/constants.pyindex 0ed6137..c611322 100644--- a/uniface/constants.py+++ b/uniface/constants.py@@ -233,6 +233,27 @@ class MiniFASNetWeights(str, Enum):V1SE = "minifasnet_v1se"V2 = "minifasnet_v2"++class EDifFIQAWeights(str, Enum):+ """+ eDifFIQA: Face Image Quality Assessment.+ Predicts a single quality score from an aligned 112x112 face.+ Higher score = better quality.++ eDifFIQA-L ranks first on the NIST FATE-Quality Kiosk-to-Entry track.+ https://github.com/yakhyo/face-image-quality-assessment++ Model Variants:+ - T: MobileFaceNet backbone (1.7M params, smallest)+ - S: IResNet-18 backbone (24.6M params)+ - M: IResNet-50 backbone (44.1M params)+ - L: IResNet-100 backbone (65.7M params, most accurate)+ """+ T = "ediffiqa_t"+ S = "ediffiqa_s"+ M = "ediffiqa_m"+ L = "ediffiqa_l"+# Centralized Model RegistryMODEL_REGISTRY: dict[Enum, ModelInfo] = {# RetinaFace@@ -482,6 +503,24 @@ MODEL_REGISTRY: dict[Enum, ModelInfo] = {url='https://github.com/yakhyo/modnet/releases/download/weights/modnet_webcam.onnx',sha256='de03cc16f3c91f25b7c2f0b42ea1a8d34f40a752234f3887572655e744e55306'),++ # eDifFIQA (Face Image Quality Assessment)+ EDifFIQAWeights.T: ModelInfo(+ url='https://github.com/yakhyo/face-image-quality-assessment/releases/download/weights/ediffiqa_t.onnx',+ sha256='7a83be63e6583ec5800fa0762e219b65b4b9f1721c4d210bfe2f16c0478832bb'+ ),+ EDifFIQAWeights.S: ModelInfo(+ url='https://github.com/yakhyo/face-image-quality-assessment/releases/download/weights/ediffiqa_s.onnx',+ sha256='1797c144f4c9b1244b5561efcab80d588a640d15cebb38dbcfdedfe65439fb47'+ ),+ EDifFIQAWeights.M: ModelInfo(+ url='https://github.com/yakhyo/face-image-quality-assessment/releases/download/weights/ediffiqa_m.onnx',+ sha256='b02ea2dcc0536d6b2480fe67ec7d8c5993bf39fe5e00f77c971a21f2701b3f37'+ ),+ EDifFIQAWeights.L: ModelInfo(+ url='https://github.com/yakhyo/face-image-quality-assessment/releases/download/weights/ediffiqa_l.onnx',+ sha256='72238239298cf645d3f5954d657b4aca7b64fd25bc808c0260778386da9b00a1'+ ),}diff --git a/uniface/draw.py b/uniface/draw.pyindex 7b92cdb..af1ebc5 100644--- a/uniface/draw.py+++ b/uniface/draw.py@@ -24,6 +24,7 @@ __all__ = ['draw_head_pose','draw_head_pose_axis','draw_head_pose_cube',+ 'draw_quality_score','draw_text_label','draw_tracks','vis_parsing_maps',@@ -579,6 +580,67 @@ def draw_head_pose()+def draw_quality_score(+ image: np.ndarray,+ bbox: list[int] | np.ndarray,+ score: float,+ *,+ draw_bbox: bool = True,+ corner_bbox: bool = True,+ low_threshold: float = 0.3,+ high_threshold: float = 0.6,+) -> None:+ """Draw a face image quality score with a color-coded label.++ Color encoding (BGR):+ - Red if score < low_threshold+ - Orange if low_threshold <= score < high_threshold+ - Green if score >= high_threshold++ Modifies the image in-place.++ Args:+ image: Input image to draw on (modified in-place).+ bbox: Face bounding box in xyxy format ``[x1, y1, x2, y2]``.+ score: Quality score in [0, 1]. Higher = better quality.+ draw_bbox: Whether to draw the bounding box. Defaults to True.+ corner_bbox: Use corner-style bounding box. Defaults to True.+ low_threshold: Below this, the label is drawn in red. Defaults to 0.3.+ high_threshold: At/above this, the label is drawn in green. Defaults to 0.6.++ Example:+ >>> from uniface.draw import draw_quality_score+ >>> draw_quality_score(image, face.bbox, result.score)+ """+ x_min, y_min, x_max, y_max = map(int, bbox[:4])++ if score < low_threshold:+ color = (0, 0, 255) # red+ elif score < high_threshold:+ color = (0, 165, 255) # orange+ else:+ color = (0, 255, 0) # green++ line_thickness = max(round(sum(image.shape[:2]) / 2 * 0.003), 2)++ if draw_bbox:+ if corner_bbox:+ draw_corner_bbox(image, bbox, color=color, thickness=line_thickness)+ else:+ cv2.rectangle(image, (x_min, y_min), (x_max, y_max), color, line_thickness)++ font_scale = max(0.4, min(0.7, (y_max - y_min) / 200))+ draw_text_label(+ image,+ f'Q:{score:.2f}',+ x_min,+ y_min,+ bg_color=color,+ text_color=(255, 255, 255),+ font_scale=font_scale,+ )++def draw_tracks(*,image: np.ndarray,diff --git a/uniface/quality/__init__.py b/uniface/quality/__init__.pynew file mode 100644index 0000000..0e64524--- /dev/null+++ b/uniface/quality/__init__.py@@ -0,0 +1,18 @@+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo++from __future__ import annotations++from uniface.constants import EDifFIQAWeights+from uniface.types import QualityResult++from .base import BaseQualityEstimator+from .ediffiqa import EDifFIQA++__all__ = [+ 'BaseQualityEstimator',+ 'EDifFIQA',+ 'EDifFIQAWeights',+ 'QualityResult',+]diff --git a/uniface/quality/base.py b/uniface/quality/base.pynew file mode 100644index 0000000..e1b2806--- /dev/null+++ b/uniface/quality/base.py@@ -0,0 +1,89 @@+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo++from __future__ import annotations++from abc import ABC, abstractmethod++import numpy as np++from uniface.types import QualityResult++__all__ = ['BaseQualityEstimator', 'QualityResult']+++class BaseQualityEstimator(ABC):+ """+ Abstract base class for face image quality assessment models.++ Quality estimators predict a single scalar score from an aligned face crop,+ where higher values indicate better quality (sharpness, frontalness,+ illumination, low occlusion). The score is typically used to filter or+ rank faces prior to recognition.+ """++ @abstractmethod+ def _initialize_model(self) -> None:+ """+ Initialize the underlying model for inference.++ This method should handle loading model weights, creating the+ inference session (e.g., ONNX Runtime), and any necessary+ setup procedures to prepare the model for prediction.++ Raises:+ RuntimeError: If the model fails to load or initialize.+ """+ raise NotImplementedError('Subclasses must implement the _initialize_model method.')++ @abstractmethod+ def preprocess(self, aligned_face: np.ndarray) -> np.ndarray:+ """+ Preprocess an aligned face crop for model inference.++ Args:+ aligned_face: An aligned face crop in BGR format, sized to the+ model's expected input (typically 112x112).++ Returns:+ The preprocessed image tensor ready for inference,+ typically with shape (1, C, H, W).+ """+ raise NotImplementedError('Subclasses must implement the preprocess method.')++ @abstractmethod+ def score_aligned(self, aligned_face: np.ndarray) -> QualityResult:+ """+ Score a pre-aligned face crop.++ Use this when the input is already aligned to the model's expected+ layout (e.g., from `uniface.face_alignment`).++ Args:+ aligned_face: Aligned face crop in BGR format.++ Returns:+ QualityResult with the predicted score.+ """+ raise NotImplementedError('Subclasses must implement the score_aligned method.')++ @abstractmethod+ def predict(self, image: np.ndarray, landmarks: np.ndarray) -> QualityResult:+ """+ Perform end-to-end quality estimation from a full image and landmarks.++ Aligns the face using the provided 5-point landmarks, then scores it.++ Args:+ image: Input image in BGR format containing the face.+ landmarks: (5, 2) array of 5-point facial landmarks for alignment.++ Returns:+ QualityResult with the predicted score.+ """+ raise NotImplementedError('Subclasses must implement the predict method.')++ def __call__(self, image: np.ndarray, landmarks: np.ndarray) -> QualityResult:+ """Callable shortcut for :meth:`predict`."""+ return self.predict(image, landmarks)diff --git a/uniface/quality/ediffiqa.py b/uniface/quality/ediffiqa.pynew file mode 100644index 0000000..6cc8eec--- /dev/null+++ b/uniface/quality/ediffiqa.py@@ -0,0 +1,143 @@+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo++from __future__ import annotations++import cv2+import numpy as np++from uniface.constants import EDifFIQAWeights+from uniface.face_utils import face_alignment+from uniface.log import Logger+from uniface.model_store import verify_model_weights+from uniface.onnx_utils import create_onnx_session+from uniface.types import QualityResult++from .base import BaseQualityEstimator++__all__ = ['EDifFIQA']+++class EDifFIQA(BaseQualityEstimator):+ """+ eDifFIQA: Face Image Quality Assessment with ONNX Runtime.++ Predicts a single scalar quality score from an aligned 112x112 face crop.+ Higher score = better quality. Supports four backbones via the+ `EDifFIQAWeights` enum (T/S/M/L).++ Paper:+ Babnik et al., "eDifFIQA: Towards Efficient Face Image Quality+ Assessment based on Denoising Diffusion Probabilistic Models",+ IEEE T-BIOM 2024. https://ieeexplore.ieee.org/document/10468647++ Code:+ https://github.com/yakhyo/face-image-quality-assessment++ Args:+ model_name: The enum specifying the model variant to load.+ Defaults to `EDifFIQAWeights.T` (smallest, ~6.6 MB).+ providers: ONNX Runtime execution providers. If None, auto-detects+ the best available provider.++ Example:+ >>> from uniface.detection import SCRFD+ >>> from uniface.quality import EDifFIQA+ >>>+ >>> detector = SCRFD()+ >>> quality = EDifFIQA()+ >>>+ >>> faces = detector.detect(image)+ >>> for face in faces:+ ... result = quality.predict(image, face.landmarks)+ ... print(f'Quality: {result.score:.4f}')+ """++ def __init__(+ self,+ model_name: EDifFIQAWeights = EDifFIQAWeights.T,+ providers: list[str] | None = None,+ ) -> None:+ Logger.info(f'Initializing EDifFIQA with model={model_name.name}')++ self.providers = providers+ self.model_path = verify_model_weights(model_name)++ # ((image / 255) - 0.5) / 0.5 == (image - 127.5) / 127.5+ self.normalization_mean = 127.5+ self.normalization_std = 127.5++ self._initialize_model()++ def _initialize_model(self) -> None:+ """+ Initialize the ONNX model from the stored model path.++ Raises:+ RuntimeError: If the model fails to load or initialize.+ """+ try:+ self.session = create_onnx_session(self.model_path, providers=self.providers)++ input_cfg = self.session.get_inputs()[0]+ self.input_name = input_cfg.name+ # Input shape is (batch, channels, height, width) - we need (width, height)+ self.input_size = tuple(input_cfg.shape[2:4][::-1])++ self.output_name = self.session.get_outputs()[0].name++ Logger.info(f'EDifFIQA initialized with input size {self.input_size}')++ except Exception as e:+ Logger.error(f"Failed to load EDifFIQA model from '{self.model_path}'", exc_info=True)+ raise RuntimeError(f'Failed to initialize EDifFIQA model: {e}') from e++ def preprocess(self, aligned_face: np.ndarray) -> np.ndarray:+ """+ Preprocess an aligned face crop for model inference.++ Converts BGR -> RGB, normalizes with mean=127.5/std=127.5, and+ reshapes to NCHW.++ Args:+ aligned_face: Aligned face crop in BGR format.++ Returns:+ Preprocessed image tensor with shape (1, 3, H, W).+ """+ return cv2.dnn.blobFromImage(+ aligned_face,+ scalefactor=1.0 / self.normalization_std,+ size=self.input_size,+ mean=(self.normalization_mean,) * 3,+ swapRB=True,+ )++ def score_aligned(self, aligned_face: np.ndarray) -> QualityResult:+ """+ Score a pre-aligned face crop.++ Args:+ aligned_face: Aligned face crop in BGR format.++ Returns:+ QualityResult with the predicted score.+ """+ blob = self.preprocess(aligned_face)+ output = self.session.run([self.output_name], {self.input_name: blob})[0]+ return QualityResult(score=float(np.squeeze(output)))++ def predict(self, image: np.ndarray, landmarks: np.ndarray) -> QualityResult:+ """+ Align the face using 5-point landmarks, then score it.++ Args:+ image: Input image in BGR format containing the face.+ landmarks: (5, 2) array of 5-point facial landmarks.++ Returns:+ QualityResult with the predicted score.+ """+ aligned, _ = face_alignment(image, landmarks.astype(np.float32))+ return self.score_aligned(aligned)diff --git a/uniface/types.py b/uniface/types.pyindex 6a3bb3a..f75e509 100644--- a/uniface/types.py+++ b/uniface/types.py@@ -29,6 +29,7 @@ __all__ = ['Face','GazeResult','HeadPoseResult',+ 'QualityResult','SpoofingResult',]@@ -84,6 +85,20 @@ class SpoofingResult:return f'SpoofingResult({label}, confidence={self.confidence:.4f})'+@dataclass(slots=True, frozen=True)+class QualityResult:+ """Result of face image quality assessment.++ Attributes:+ score: Quality score in [0, 1]. Higher = better quality.+ """++ score: float++ def __repr__(self) -> str:+ return f'QualityResult(score={self.score:.4f})'++@dataclass(slots=True, frozen=True)class EmotionResult:"""Result of emotion recognition.@@ -171,6 +186,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).+ quality: Face image quality score in [0, 1] (optional, from eDifFIQA).track_id: Persistent track ID assigned by BYTETracker (optional).Properties:@@ -192,6 +208,7 @@ class Face:race: str | None = Noneemotion: str | None = Noneemotion_confidence: float | None = None+ quality: float | None = Nonetrack_id: int | None = Nonedef compute_similarity(self, other: Face) -> float:@@ -263,6 +280,8 @@ class Face:parts.append(f'race={self.race}')if self.emotion is not None:parts.append(f'emotion={self.emotion}')+ if self.quality is not None:+ parts.append(f'quality={self.quality:.4f}')if self.embedding is not None:parts.append(f'embedding_dim={self.embedding.shape[-1]}')return ', '.join(parts) + ')'