* docs: Minor info changes * refactor: Remove deprecated factory functions Removes the 10 factory functions deprecated in v3.7.0: create_detector, list_available_detectors, create_recognizer, create_face_parser, create_gaze_estimator, create_head_pose_estimator, create_landmarker, create_matting_model, create_spoofer, create_attribute_predictor. Instantiate model classes directly instead, e.g. `from uniface.detection import SCRFD; SCRFD()`. Also drops the now-unused typing_extensions dependency and updates docstring examples that referenced the factories. * refactor: Remove MODEL_URLS and MODEL_SHA256 back-compat mirrors Use MODEL_REGISTRY instead of the MODEL_URLS and MODEL_SHA256 dicts in uniface.constants. * chore: Add .claude directory to gitignore * ci: Deploy docs via GitHub Pages artifact instead of gh-pages branch * feat: Add FaceAttribNet face state prediction model Integrate Qualcomm's FaceAttribNet (Facial-Attribute-Detection) as a new attribute model predicting five independent binary face states from a face crop: left/right eye openness, eyeglasses, mask, and sunglasses. - Add FaceAttribNet class with letterbox preprocessing (normalization is baked into the ONNX graph) and multi-label FaceStateResult output - Register FaceAttribNetWeights with dynamic-batch ONNX weights (opset 17) - Enrich Face with left_eye_open, right_eye_open, eyeglasses, mask, and sunglasses fields - Rename AttributeResult to DemographyResult and DDAMFNWeights to EmotionWeights so 'attribute' unambiguously means the model category - Add tests and docs * docs: Add face attributes notebook, demo assets, and README updates * feat: Add CenterFace face detection model * docs: Add CONTEXT.md glossary and ADRs for v4 naming decisions ADR-0001: Face.landmarks keeps its v3 name for the 5-point set; the future dense-landmark slot will be Face.dense_landmarks. ADR-0002: Attribute stays the per-face predictor base class name; FaceAnalyzer(attributes=...) is unchanged. * refactor: Rename FaceAnalyzer attributes parameter to predictors The pipeline parameter names the role (per-face predictors), so future head pose, gaze, spoofing, and quality models can be passed without the semantic mismatch of being listed as attributes. The Attribute base class keeps its name per ADR-0002. BREAKING CHANGE: FaceAnalyzer(attributes=...) is now FaceAnalyzer(predictors=...); FaceAnalyzer.attributes is now FaceAnalyzer.predictors. * docs: Update docs and notebooks for predictors parameter rename * docs: Remove CONTEXT.md * docs: Restore README badges * docs: Remove ADR folder * refactor: Rename Attribute base class to BaseAttribute * docs: Replace thick README separators with heading underlines * docs: Put README tagline in a callout * fix: Use predictors= in the analyze tool * refactor: Make supports_landmarks a class attribute on BaseDetector Replaces the private _supports_landmarks instance flag and its read-only property with a plain class attribute, mirroring supports_alignment. Every detector set the flag to True in __init__, so the False default never survived and the hasattr guard in the property was dead weight. Also drops a stale Attributes entry in RetinaFace for a field that no longer exists, and removes comments that restated the call beneath them. * docs: Normalize docstring markup and document missing raises Audited every docstring and comment in uniface/ against the detection package, which is the most internally consistent one. - Replace 13 Sphinx roles and 159 RST double-backticks with markdown backticks; nothing renders docstrings, there is no Sphinx, and mkdocs has no mkdocstrings plugin - Rewrite 59 legacy typing generics (List, Tuple, Optional, Union) to PEP 585, each checked against the real signature rather than mechanically substituted - Add Raises sections to download_file, compute_similarity and parse_with_inverse, which raised undocumented exceptions - Drop the RuntimeError Raises block from six abstract _initialize_model methods whose body raises NotImplementedError; the contract belongs to the implementer and is now stated as prose - Fold Properties into Attributes with a Read-only prefix, singularize Examples, and fix the copyright year in faceattribnet No executable line changed; the bulk pass rewrote only string and comment tokens matched by byte offset. * fix: Raise ValueError instead of asserting in estimate_norm Both input checks used bare assert statements, which python -O strips. The docstring promised AssertionError as part of the contract, so under an optimized build the validation silently disappeared and an unsupported image_size flowed into the alignment maths instead of failing fast. Both are now ValueError, and the messages report the offending value. * docs: Replace RST double-backticks in face_utils * docs: Document Raises on every model class The detection package documents ValueError and RuntimeError on the class docstring; no model class in any other package did, even though they all call verify_model_weights in __init__ and reach an _initialize_model that wraps session creation in RuntimeError. Verified per class before adding: each target reaches both raise sites, inheriting _initialize_model from its base where it does not define one. * fix: Replace the last two bare asserts with explicit raises python -O strips assert statements, so both checks silently disappeared in optimized builds. BaseRecognizer would then accept a multi-output model and mis-slice its results, and get_meanface_info would build neighbour tables from a meanface of the wrong length. Behaviour is unchanged in normal builds: the recognizer check already sat inside the try that re-raises as RuntimeError, and the meanface check now raises the ValueError its docstring already documented. No bare asserts remain in uniface/. * style: Put multi-line docstring summaries on the first line Card 6 of the docstring audit: class docstrings opened two different ways, 45 with a leading newline and 37 on the same line as the quotes. Settled by the repo's own config rather than by taste. pyproject already declares pydocstyle convention = google, under which ruff resolves D212 (multi-line-summary-first-line) as the active rule and explicitly ignores the incompatible D213. Same-line was therefore already the declared standard, even though the detection package -- the audit's exemplar -- sat on the other side of the split. Applied with ruff --fix, then the summaries that ended up glued to their description got the blank line D205 wants. * style: Put multi-line docstring summaries on the first line (constants, test_utils) Same D212/D205 pass as the previous commit, applied to the two files that were held back from it. * build: Enforce D205 and D212 in ruff The docstring audit found the opening style split 45/37 with nothing to hold it in place: pyproject declared pydocstyle convention = google, but D was absent from select, so the convention setting was inert. Selecting the two rules the codebase now satisfies makes the decision checkable instead of conventional. The rest of D is left off deliberately -- D100 alone would flag 63 files, since this project's convention is to have no module docstrings. * feat: Add BlazeFace detector and MediaPipe Face Mesh landmarker BlazeFace is MediaPipe's short-range SSD face detector: two anchor grids over a 128x128 letterboxed image, decoded with MediaPipe's weighted NMS where overlapping candidates are score-averaged rather than discarded. It emits 6 MediaPipe keypoints, not the 5-point alignment template, so BaseDetector gains a supports_alignment flag. It is True everywhere else and False only here. FaceAnalyzer checks it and disables recognition with a warning instead of producing broken embeddings, and estimate_norm's error now names the constraint when a caller tries to align anyway. FaceMesh predicts 468 dense 3D landmarks from a face crop and is detector-agnostic: the ROI follows MediaPipe's recipe, a square region at 1.5x the detector box rotated so the eye line is horizontal, built from whichever two eye points the detector provides. Every face in an image runs in one session call. roi_from_box and warp_roi are public so video-mode tracking can be built on top. Also adds FaceMeshResult, draw_mesh with full and partial tessellations, weight entries for both models, the facemesh and facestate tools, example notebook 15, and tests for both models. Tessellation tables are vendored from PINTO0309/facemesh_onnx_tensorrt (Apache-2.0); provenance is recorded in docs/license-attribution.md. * docs: List BlazeFace and Face Mesh in the remaining model indexes The feature commit updated the detection and landmarks module pages, the model zoo and the concept pages, but four summary listings still predated both models: - README examples table stopped at notebook 14 - README training-dataset table omitted both - quickstart model summary omitted both - index.md feature cards described detection as 5-point only, which BlazeFace's 6 keypoints contradict * feat: Add MediaPipe Face Landmarker, a 478-point mesh with irises Google's Face Landmarker is the successor to Face Mesh: one network predicting 478 landmarks from a 256x256 crop, where the first 468 keep the Face Mesh topology and ordering and the last ten are the irises. It ships in the Tasks API bundle; the earlier 478-point attention model is not ported, since it needs three MediaPipe-only TFLite custom ops that no standard runtime can load. FaceMesh needs no logic change to serve it. Input size and landmark count were already read from the ONNX graph, so 192->256 and 468->478 are absorbed at load time. Verified end to end at 0.007% of inter-ocular distance against MediaPipe's own pipeline, with the existing ROI recipe unchanged - Google's model card specifies the same 25% per-side margin the default already used. Iris membership follows MediaPipe's own convention: the result stays a flat array and the region lives in named constants next to the topology it indexes, rather than becoming accessors on FaceMeshResult. draw_mesh renders the irises distinctly, so the library and tools/facemesh.py agree by construction. BREAKING CHANGE: FaceMeshWeights.DEFAULT is replaced by V1_468 and V2_478. Default behaviour is unchanged - the constructor still loads the 468-point model - but code naming DEFAULT explicitly must be updated. Every other multi-variant weights enum already names its members descriptively. * feat: Add Hugging Face mirror fallback for weight downloads * docs: Document the Hugging Face mirror fallback * fix: Resolve bugs found in whole-codebase review * refactor: Publish validate_image and normalize line endings * fix: Guarantee weighted NMS terminates * refactor: Make model constructors keyword-only * refactor: Read input_size from the ONNX model * fix: Normalize and validate attribute input_size * refactor: Replace detector **kwargs with explicit options * fix: Reject unusable images in BlazeFace and FaceMesh * feat: Make detector capability flags opt-in * fix: Show every populated face state in Face repr * docs: Clarify inline comments * docs: Update docs and notebooks for v4 * refactor: Make remaining public constructors keyword-only * feat: Export BaseAttribute and document custom predictors * test: Cover FaceAnalyzer predictors * fix: Pin the Hugging Face mirror to an immutable revision * docs: Add changelog with v4 migration guide * ci: Deploy release docs via the Pages artifact flow * build: Require setuptools 77 for the SPDX license field * docs: Fix anchors, dataset table, and tool options * chore: Release v4.0.0rc1 --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
5.6 KiB
Coordinate Systems
This page explains the coordinate formats used in UniFace.
Image Coordinates
All coordinates use pixel-based, top-left origin:
(0, 0) ────────────────► x (width)
│
│ Image
│
▼
y (height)
Bounding Box Format
Bounding boxes use [x1, y1, x2, y2] format (top-left and bottom-right corners):
(x1, y1) ─────────────────┐
│ │
│ Face │
│ │
└─────────────────────┘ (x2, y2)
Accessing Coordinates
face = faces[0]
# Direct access
x1, y1, x2, y2 = face.bbox
# As properties
bbox_xyxy = face.bbox_xyxy # [x1, y1, x2, y2]
bbox_xywh = face.bbox_xywh # [x1, y1, width, height]
Conversion
import numpy as np
# xyxy → xywh
def xyxy_to_xywh(bbox):
x1, y1, x2, y2 = bbox
return np.array([x1, y1, x2 - x1, y2 - y1])
# xywh → xyxy
def xywh_to_xyxy(bbox):
x, y, w, h = bbox
return np.array([x, y, x + w, y + h])
Landmarks
5-Point Landmarks (Detection)
Returned by all detection models:
landmarks = face.landmarks # Shape: (5, 2)
| Index | Point |
|---|---|
| 0 | Left Eye |
| 1 | Right Eye |
| 2 | Nose Tip |
| 3 | Left Mouth Corner |
| 4 | Right Mouth Corner |
0 ● ● 1
● 2
3 ● ● 4
This ordering is the alignment template (uniface.face_utils.reference_alignment)
that recognition, quality scoring, and XSeg parsing all require.
!!! warning "BlazeFace uses a different layout"
BlazeFace returns 6 keypoints — right eye, left eye, nose tip, mouth center,
right ear tragion, left ear tragion — named from the subject's perspective, so rows
0/1 are still the viewer-left and viewer-right eye. With no mouth corners they
cannot be fitted to the template above, which is why BlazeFace.supports_alignment
is False.
106-Point Landmarks
Returned by Landmark106:
from uniface.landmark import Landmark106
landmarker = Landmark106()
landmarks = landmarker.get_landmarks(image, face.bbox)
# Shape: (106, 2)
Landmark Groups:
| Range | Group | Points |
|---|---|---|
| 0-32 | Face Contour | 33 |
| 33-50 | Eyebrows | 18 |
| 51-62 | Nose | 12 |
| 63-86 | Eyes | 24 |
| 87-105 | Mouth | 19 |
98 / 68-Point Landmarks (PIPNet)
Returned by PIPNet. The variant determines the layout:
from uniface.constants import PIPNetWeights
from uniface.landmark import PIPNet
# 98-point WFLW layout (default)
landmarks = PIPNet().get_landmarks(image, face.bbox)
# Shape: (98, 2)
# 68-point 300W layout
landmarks = PIPNet(model_name=PIPNetWeights.DW300_CELEBA_68).get_landmarks(image, face.bbox)
# Shape: (68, 2)
The 98-point output follows the standard WFLW layout
(33 face-contour points, eyebrow/eye/nose/mouth groups). The 68-point output follows the standard
300W / iBUG layout. Coordinates are in original-image
pixel space, identical in convention to Landmark106.
468-Point Landmarks (Face Mesh)
FaceMesh is the only model in UniFace that returns three coordinates per point:
from uniface import FaceMesh
results = FaceMesh().predict(image, faces)
results[0].landmarks # Shape: (468, 3)
| Axis | Meaning |
|---|---|
x, y |
Original-image pixel coordinates, same convention as every other landmarker |
z |
Relative depth, on the same pixel scale as x/y. Smaller is closer to the camera |
z has no absolute origin — it is only meaningful within one face, for comparing which
features sit nearer the camera. It is not a distance measurement and is not comparable
between faces or between images. Use results[0].points_2d to drop it.
Face Crop
To crop a face from an image:
def crop_face(image, bbox, margin=0):
"""Crop face with optional margin."""
h, w = image.shape[:2]
x1, y1, x2, y2 = map(int, bbox)
# Add margin
if margin > 0:
bw, bh = x2 - x1, y2 - y1
x1 = max(0, x1 - int(bw * margin))
y1 = max(0, y1 - int(bh * margin))
x2 = min(w, x2 + int(bw * margin))
y2 = min(h, y2 + int(bh * margin))
return image[y1:y2, x1:x2]
# Usage
face_crop = crop_face(image, face.bbox, margin=0.1)
Gaze Angles
Gaze estimation returns pitch and yaw in radians:
result = gaze_estimator.estimate(face_crop)
# Angles in radians
pitch = result.pitch # Vertical: + = up, - = down
yaw = result.yaw # Horizontal: + = right, - = left
# Convert to degrees
import numpy as np
pitch_deg = np.degrees(pitch)
yaw_deg = np.degrees(yaw)
Angle Reference:
pitch = +90° (up)
│
│
yaw = -90° ────┼──── yaw = +90°
(left) │ (right)
│
pitch = -90° (down)
Face Alignment
Face alignment uses 5-point landmarks to normalize face orientation:
from uniface.face_utils import face_alignment
# Align face to standard template
aligned_face, _ = face_alignment(image, face.landmarks)
# Output: (112x112 aligned face image, inverse transform matrix)
The alignment transforms faces to a canonical pose for better recognition accuracy.
Next Steps
- Inputs & Outputs - Data types reference
- Recognition Module - Face recognition details