Facial Analysis & Data Export¶
Raw (x, y) landmark pixels are rarely what you put directly into a statistical model or ethogram. PrimateFace automatically converts those 68 points into biologically meaningful variables — mouth opening, brow height, head turn, facial symmetry, and image quality — and exports them straight to Excel/R (CSV), COCO JSON, DeepLabCut / Lightning Pose, SLEAP, or NWB.
Do I need a GPU?
No. Once landmarks have been extracted, every analysis metric, temporal smoother, and file exporter on this page runs in milliseconds on a regular laptop CPU.
Automatic (Face) Properties¶
When you run pf.analyze("monkey.jpg"), each returned Face object computes its derived measurements lazily — meaning nothing extra runs until you ask for a property, and once computed the result is cached:
import primateface
pf = primateface.PrimateFace()
face = pf.analyze("demos/ateles_000003.jpeg")[0]
print("Head pose (yaw, pitch, roll):", tuple(round(a, 1) for a in face.head_pose))
print("Mouth aperture (IOD-norm): ", round(face.kinematics["mouth_aperture"], 3))
print("Fluctuating asymmetry: ", round(face.symmetry, 4))
print("Composite quality score: ", round(face.quality["score"], 2))
Expected output:
Head pose (yaw, pitch, roll): (4.8, -2.3, 1.1)
Mouth aperture (IOD-norm): 0.084
Fluctuating asymmetry: 0.0312
Composite quality score: 0.91
Convenience shortcuts face.mouth_aperture, face.eye_aperture, face.brow_position, face.interocular_distance, and face.region_symmetry are also available directly on every Face.
14 Kinematic & Morphological Features¶
Accessing face.kinematics (or calling extract_kinematics(keypoints)) returns 14 named measurements covering facial expressions and craniofacial proportions:
| Feature Key | What It Measures | Scale | Common Biological Use |
|---|---|---|---|
mouth_aperture | Inner upper lip (62) to inner lower lip (66) | ÷ IOD | Vocalizations, lip-smacking, yawns |
mouth_width | Right (48) to left (54) mouth corner (animal's anatomical right/left, matching the 68-point map) | ÷ IOD | Bared-teeth grins, lip stretching |
mouth_aspect_ratio | mouth_aperture / mouth_width | Ratio | Distinguishing wide vs. tall mouth openings |
right_eye_aperture | Mean upper–lower eyelid spacing (right eye) | ÷ IOD | Blinks, squinting, vigilance |
left_eye_aperture | Mean upper–lower eyelid spacing (left eye) | ÷ IOD | Blinks, squinting, vigilance |
right_brow_height | Right eyebrow center to right eye center | ÷ IOD | Brow-raise displays (AU1/AU2 [FACS brow-raise units] proxy) |
left_brow_height | Left eyebrow center to left eye center | ÷ IOD | Brow-raise displays (AU1/AU2 [FACS brow-raise units] proxy) |
face_height | Chin (8) to top of nose bridge (27) | ÷ IOD | Facial elongation / ontogeny |
face_width | Widest jaw span (1–15 or 2–14) | ÷ IOD | Sex/age dimorphism |
face_aspect_ratio | face_height / face_width | Ratio | Infant (rounder) vs. adult (elongated) shape |
jaw_width | Lower jaw span (4–12) | ÷ IOD | Jaw dimorphism |
nose_length | Nose bridge (27) to nose tip (30) | ÷ IOD | Taxonomic / morphological proportions |
eye_to_mouth | Eye midpoint to mouth midpoint | ÷ IOD | Mid-face length |
interocular_distance | Distance between eye centers | Pixels | Size anchor (IOD) for normalizing distances |
Why Divide by Interocular Distance (IOD)?¶
If a monkey walks twice as close to the camera (or you zoom in 2×), every pixel distance doubles even though the animal's expression has not changed. Dividing facial distances by interocular_distance (IOD) — the rigid spacing between the eyes — removes camera-distance and zoom bias so frames from different videos can be compared on one anatomical scale.
Wide-open vocalizations: use jaw-invariant rolling-median IOD
During extreme vocal displays (such as howler monkey roars), normalizing by the rolling median of interocular_distance over surrounding video frames gives a stable, jaw-invariant scale anchor unaffected by jaw drop or brief single-frame eye jitter. See the howler vocal-motor notebook in Tutorials.
Video Time-Series, Smoothing & Lip-Smack Detection¶
For video sequences, first collect per-frame landmarks into an (N_frames, 68, 3) array with OpenCV (cv2.VideoCapture), then smooth frame-to-frame jitter with MedianSavgolSmoother, extract a full kinematic table with extract_timeseries, and optionally flag rhythmic 3–8 Hz lip-smacking bouts with detect_lip_smack:
import cv2, numpy as np, primateface
from primateface._smooth import MedianSavgolSmoother
from primateface.analysis.kinematics import extract_timeseries, detect_lip_smack
# 0. Collect per-frame (68, 3) landmarks from a video
pf = primateface.PrimateFace(pose_model="rtmpose")
cap = cv2.VideoCapture("clip.mp4")
frames = []
while True:
ok, frame = cap.read()
if not ok:
break
faces = pf.analyze(frame)
frames.append(faces[0].keypoints if faces else np.full((68, 3), np.nan))
cap.release()
raw_kpts = np.stack(frames) # shape (N_frames, 68, 3)
# 1. Remove single-frame jitter (NaN-safe for low-confidence points, zero lag)
smoother = MedianSavgolSmoother(median_window=5, savgol_window=7, savgol_order=1)
smoothed = np.stack([
smoother.update(instance_id=0, keypoints=k[:, :2], keypoint_scores=k[:, 2], kpt_thr=0.3)
for k in raw_kpts
])
# 2. Build a per-frame DataFrame and detect 3-8 Hz lip-smack episodes
ts = extract_timeseries(smoothed, fps=30.0)
episodes = detect_lip_smack(ts, fps=30.0)
print(f"Extracted {len(ts)} frames; detected {len(episodes)} lip-smack bout(s): {episodes}")
Expected output:
Head Pose, Symmetry & Frame Quality Filtering¶
- Head pose (
estimate_head_pose/face.head_pose): Returns(yaw, pitch, roll)in degrees — horizontal left/right turn, vertical up/down tilt, and sideways head roll — using 6 anchor landmarks and a 3D perspective solver (cv2.solvePnP). - Facial symmetry (
facial_symmetry,per_region_symmetry): Measures fluctuating asymmetry (0.0= perfect left-right symmetry, normalized by IOD), either globally (method="midline"or"procrustes") or separately acrossjaw,eyebrows,eyes,nose, andmouth. - Quality filtering (
face_quality/face.quality): Returnsblur(Laplacian sharpness, an edge-sharpness score; >500 is crisp),size(face fraction of frame),visibility(share of visible landmarks),brightness(0–255), and compositescore(0–1).
# Filter out blurry, tiny, or strongly turned faces before statistical analysis
clean_faces = [
f for f in all_faces
if f.quality["score"] >= 0.6 and abs(f.head_pose[0]) <= 30.0
]
Optional Face Embeddings (Individual Re-Identification)¶
You can attach an optional face-recognition embedding model (embedding_model="arcface" for 512-d InsightFace vectors or "megadescriptor" for 1536-d wildlife vectors) to compare two faces via face.embedding and face.verify(other_face) using cosine distance (0 = identical, higher = more different):
import primateface
pf = primateface.PrimateFace(embedding_model="arcface") # or "megadescriptor"
f1 = pf.analyze("macaque_a.jpg")[0]
f2 = pf.analyze("macaque_b.jpg")[0]
same_id, cos_dist = f1.verify(f2, threshold=0.4)
print(f"Same individual: {same_id} (cosine distance={cos_dist:.3f})")
Expected output:
Validate locally for individual ID
Closed-set individual recognition requires labeled reference images of your known animals and local threshold validation across lighting and pose conditions. Do not treat default similarity thresholds as universally calibrated across species (see Scope & Limitations).
Exporting & Importing Data (primateface.io)¶
primateface.io converts Face lists directly into spreadsheets and every major ethology / neuroscience pose format:
| Format | Export Function | Import Function | Best For |
|---|---|---|---|
| pandas DataFrame | to_dataframe(faces) | — | Immediate Python analysis & plotting |
| CSV spreadsheet | to_csv(faces, path) | pandas.read_csv / R read.csv | Excel, R (tidyverse), Prism, SPSS |
| COCO JSON | to_coco_json(faces, path) | from_coco_json(path) | MMPose, RF-DETR, CVAT (free web annotation tool), GUI review |
| DeepLabCut / Lightning Pose | to_dlc_csv, to_dlc_h5 | from_dlc(path) | MultiIndex DLC 3.0 & Lightning Pose 2.0 |
SLEAP (.slp) | to_sleap(faces, path) | from_sleap(path) | SLEAP GUI & tracking (needs sleap-io) |
NWB (.nwb) | to_nwb(faces, path) | from_nwb(path) | Neurodata Without Borders (needs pynwb, ndx-pose) |
from primateface.io import to_csv, to_coco_json, to_dlc_csv, to_sleap, to_nwb
to_csv(faces, "results.csv", image_path="monkey.jpg") # Ready for Excel or R
to_coco_json(faces, "results.json", image_path="monkey.jpg")
to_dlc_csv(faces, "results_dlc.csv") # Also Lightning Pose compatible
to_sleap(faces, "results.slp") # uv pip install -e ".[interop]"
to_nwb(faces, "session.nwb", session_description="Macaque vocalization session") # uv pip install -e ".[interop]"
Next Steps¶
- See full function signatures in the API Reference.
- Walk through complete biological case studies (howler vocalizations, macaque recognition, dyadic interactions) in Interactive Tutorials.