Python API & CLI Reference¶
PrimateFace turns primate photos or video frames into face bounding boxes (rectangles around each face), 68 facial landmarks (anatomical coordinates around the jaw, brows, eyes, nose, and mouth), biological measurements (mouth opening, head angle, facial symmetry, image quality), and files ready for spreadsheets or pose-tracking software.
Do I need a GPU?
No for small jobs; yes (or free Google Colab) for large batches or video. Passing device="cpu" works on any laptop for single images (typically 1–3 seconds per photo with the default hrnet model). For folders of hundreds of images, video tracking, or the heavier vitpose model, use an NVIDIA GPU or a free Google Colab T4 GPU. See Installation and Quickstart.
Minimal End-to-End Example¶
import primateface
pf = primateface.PrimateFace() # Downloads RF-DETR-M + HRNet on first run
faces = pf.analyze("monkey.jpg") # Detects all primate faces & 68 landmarks
print(faces[0])
print("Mouth aperture:", round(faces[0].mouth_aperture, 3))
print("Head pose (yaw, pitch, roll):", tuple(round(a, 1) for a in faces[0].head_pose))
primateface.PrimateFace.draw(faces, "monkey.jpg", output="annotated.jpg")
Expected output:
Face(score=0.96, bbox=[142, 88, 398, 354], landmarks=68)
Mouth aperture: 0.142
Head pose (yaw, pitch, roll): (4.8, -2.3, 1.1)
PrimateFace (primateface.core)¶
The main entry point that downloads verified checkpoints from Hugging Face, runs face detection and 68-point landmark estimation, and returns a list of Face objects.
PrimateFace(
device=None,
pose_model="hrnet",
det_model="rfdetr",
embedding_model=None,
det_threshold=0.5,
nms_threshold=0.3,
model_dir=None,
)
| Parameter | Accepted Values | Default | Plain-English Meaning |
|---|---|---|---|
device | "cuda:0", "cpu", or None | None | Compute hardware (None auto-selects GPU if available, else CPU). |
det_model | "rfdetr", "rfdetr-m", "cascade_rcnn" | "rfdetr" | Face detector. "rfdetr" / "rfdetr-m" loads canonical RF-DETR-M v1.0.0 (Apache-2.0, 137 MB); "cascade_rcnn" loads the legacy v0.1.0 MMDetection comparator. |
pose_model | "hrnet", "rtmpose", "vitpose" | "hrnet" | 68-point landmark model: "hrnet" (41 MB, lightweight), "rtmpose" (62 MB, fastest), "vitpose" (1.23 GB, highest accuracy). See Model Zoo. |
embedding_model | None, "arcface", "megadescriptor" | None | Optional identity-vector model for individual recognition ("arcface" = 512-d, needs insightface; "megadescriptor" = 1536-d, needs timm). |
det_threshold | float in (0, 1) | 0.5 | Minimum confidence score to keep a detected face (raise to reduce false alarms, lower to catch distant faces). |
nms_threshold | float in (0, 1) | 0.3 | Non-Maximum Suppression (NMS) overlap threshold—merges duplicate boxes drawn on the same face. |
model_dir | Path string, Path, or None | None | Local folder for offline checkpoints (None caches automatically in ~/.cache/huggingface/). |
Methods¶
pf.analyze(image, det_threshold=None, nms_threshold=None) -> list[Face]— Accepts a file path (str/Path), OpenCV BGR NumPy array (note: OpenCV uses BGR channel order, whereas PIL andmatplotlibuse RGB—pass a PIL Image or convert RGB arrays viaimg[:, :, ::-1]), or PIL Image. ReturnsFaceobjects sorted by confidence (highest first), or[]if no face is found.pf.analyze_batch(images) -> list[list[Face]]— Convenience wrapper that runsanalyze()on a sequence of images and returns onelist[Face]per image.PrimateFace.draw(faces, image, output=None, draw_keypoints=True, draw_skeleton=True, draw_bbox=True, show_pose=False) -> np.ndarray— Static helper that draws boxes, 68 landmarks, facial contours, or a 3D head-orientation wireframe (show_pose=True) ontoimage, optionally saving tooutputand returning an OpenCV BGR NumPy array (convert viacv2.cvtColor(arr, cv2.COLOR_BGR2RGB)before displaying withmatplotlib).
Face (primateface.face)¶
A lightweight container (Python dataclass) representing one detected primate face. Derived measurements are lazy properties: they are calculated only when you access them and then cached, so unused metrics add zero runtime cost.
| Attribute / Property | Return Type | Plain-English Meaning |
|---|---|---|
bbox | np.ndarray (4,) | Face box [x1, y1, x2, y2] in pixel coordinates. |
score | float | Detector confidence in [0, 1]. |
keypoints | np.ndarray (68, 3) | 68 facial landmarks as [x, y, confidence] per point. |
crop | np.ndarray | Tightly cropped BGR image of this face. |
head_pose | (yaw, pitch, roll) | Approximate 3D head orientation in degrees (turn, tilt, roll). |
kinematics | dict[str, float] | All 14 geometric/kinematic features normalized by interocular distance (IOD = distance between eye centers, making values comparable across camera distances). |
mouth_aperture | float | Vertical inner-lip opening (IOD-normalized). |
eye_aperture | (right, left) | Vertical eyelid openings for right and left eyes (IOD-normalized). |
brow_position | (right, left) | Eyebrow height above each eye (IOD-normalized). |
interocular_distance | float | Distance between left and right eye centers in pixels. |
symmetry | float | Overall fluctuating asymmetry (0 = perfectly symmetric; higher = more asymmetric). |
region_symmetry | dict[str, float] | Asymmetry broken down by jaw, eyebrows, eyes, nose, and mouth. |
quality | dict[str, float] | Blur (sharpness), relative face size, landmark visibility, brightness, and composite score in [0, 1]. |
embedding | np.ndarray | Identity vector (requires embedding_model set in PrimateFace(...)). |
verify(other, threshold=0.4) | (bool, float) | Compares this face to another Face via cosine distance; returns (is_same, distance). |
to_dict() | dict | Plain JSON-serializable dict (bbox, score, keypoints), excluding raw image pixels. |
Export & Import (primateface.io)¶
Save Face detections directly to spreadsheets or behavioral pose-tracking formats, or read predictions back into a pandas DataFrame. See the Analysis & I/O Guide for worked examples.
| Function | Format | Direction | Notes |
|---|---|---|---|
to_dataframe(faces, image_path=None, ...) | pandas.DataFrame | Export | One row per face; optional kinematics, head pose, quality, symmetry columns. |
to_csv(faces, output_path, image_path=None, **kwargs) | CSV spreadsheet | Export | Opens directly in Excel, R, or Python. |
to_coco_json(faces, output_path, image_path=None, image_id=1) | COCO JSON | Export | Standard computer-vision annotation format ([x, y, w, h] boxes + 68 landmarks). |
from_coco_json(json_path) | COCO JSON | Import | Loads boxes and landmark columns into a DataFrame. |
to_dlc_csv(faces, output_path, scorer="primateface") | DeepLabCut / Lightning Pose CSV | Export | MultiIndex (scorer, bodyparts, coords) CSV compatible with both DLC and LP. |
to_dlc_h5(faces, output_path, scorer="primateface") | DeepLabCut / Lightning Pose HDF5 | Export | Compact binary .h5 (key="df_with_missing"). |
from_dlc(h5_or_csv_path) | DeepLabCut / Lightning Pose | Import | Reads .h5, .hdf5, or .csv MultiIndex predictions. |
to_sleap(faces, output_path, video_path=None, frame_idx=0) | SLEAP .slp | Export | Requires uv pip install -e ".[interop]" (sleap-io). |
from_sleap(slp_path) | SLEAP .slp | Import | Loads frame/instance landmarks from .slp into a DataFrame. |
to_nwb(faces, output_path, session_description=..., timestamps=None) | NWB .nwb (ndx-pose) | Export | Neurodata Without Borders format; requires uv pip install -e ".[interop]". |
from_nwb(nwb_path, pose_estimation_name=None) | NWB .nwb | Import | Reads PoseEstimation timestamps, coordinates, and confidences. |
Landmark Analysis Modules (primateface.analysis)¶
If you already have 68-point landmarks as NumPy arrays of shape (68, 2) or (68, 3) (for instance, from COCO JSON or DeepLabCut), call these functions directly without loading neural networks:
| Module | Key Functions | Biological Output |
|---|---|---|
primateface.analysis.kinematics | extract_kinematics, extract_timeseries, detect_lip_smack, mouth_aperture, mouth_width, mouth_aspect_ratio, eye_aperture, brow_height, face_height, face_width, face_aspect_ratio, jaw_width, nose_length, eye_to_mouth | Frame-level facial ratios, video time series (frame, time_s, 14 features), and 3–8 Hz rhythmic lip-smack episode detection. |
primateface.analysis.symmetry | facial_symmetry(kpts, method="midline"\|"procrustes"), per_region_symmetry(kpts) | Fluctuating asymmetry across the full face or per anatomical region. |
primateface.analysis.head_pose | estimate_head_pose(kpts, image_size, camera_matrix=None, dist_coeffs=None) | Approximate (yaw, pitch, roll) in degrees via 6-point cv2.solvePnP. |
primateface.analysis.quality | face_quality(image, bbox, kpts) | Dict with blur, size, visibility, brightness, and composite score. |
primateface.analysis.utils | load_keypoints_from_coco, interocular_distance, get_eye_centers, normalize_distance, fit_midline, point_to_line_distance, visibility_ratio | Loading COCO landmark arrays, eye-center scaling, midline geometry, and visibility fractions. |
Command-Line Interfaces¶
Installed primateface CLI¶
Run directly from your terminal without writing Python:
# Analyze a single image or a whole folder and save annotated visualizations
primateface analyze monkey.jpg -o annotated.jpg \
--det-model rfdetr --pose-model hrnet --det-threshold 0.5 --device cuda:0
# Inspect all registered v1.0.0 models hosted on Hugging Face
primateface models list
Supported primateface analyze flags: input (image file or folder), -o/--output, --det-model {rfdetr,cascade_rcnn}, --pose-model {hrnet,rtmpose,vitpose}, --det-threshold FLOAT (default 0.5), --model-dir DIR, and --device DEVICE.
Repository Script CLIs (demos/ and landmark-converter/)
When working from a cloned GitHub repository, additional standalone CLIs cover video processing, genus classification, attribute heads, bulk downloads, and 68→48 landmark conversion:
demos/primateface_demo.py— Subcommandsprocess(images/folders/videos with--smoothtemporal filtering,--save-predictions,--save-viz),classify(69-genus ConvNeXt-Small with--min-confabstention), andvisualize(render COCO JSON overlays).demos/download_models.py— Pre-download verifiedv1.0.0weights locally (--include-vitpose,--include-cross-platform,--include-legacy,--all,--force,--no-verify).demos/classify_genus.py— Standalone 69-genus classifier on face crops (python demos/classify_genus.py crops/ preds.json --checkpoint primateface_genus_convnext_s_v1.0.0.pth --min-conf 0.85). See Genus & Attributes.demos/train_attribute_heads.py— Subcommandstrainandpredictfor the 6 observable facial-attribute MLP heads on precomputed features (--features,--labels,--out-dir,--group-col).landmark-converter/convert_coco_68to48.py— Convert 68-point COCO JSON annotations into 48-point landmarks (--model-path,--coco-json,--image-dir,--output-dir,--save-png). See Landmark Conversion.