Quickstart¶
In 5 minutes, you will detect a primate face in a single photograph, place 68 anatomical landmarks, extract biological measurements (head turn, mouth opening, eye opening, brow height, symmetry, and image quality), save an annotated figure, and export a spreadsheet ready for Excel or R.
No local installation yet?
You can run this exact walkthrough in your browser on a free Google Colab GPU—see the Interactive Tutorials. Locally, this walkthrough works on both a regular laptop CPU (a few seconds for one photo) and an NVIDIA GPU (fractions of a second).
The repository includes a sample spider monkey photo at demos/ateles_000003.jpeg. You can use it below or swap in any .jpg or .png photo of your own.
Step 1: Detect faces and place 68 landmarks¶
Open Python (or a Jupyter notebook) in your PrimateFace environment and run:
import primateface
pf = primateface.PrimateFace(det_model="rfdetr", pose_model="hrnet")
faces = pf.analyze("demos/ateles_000003.jpeg")
print(f"Found {len(faces)} face(s)")
Expected output:
On your first run, PrimateFace automatically downloads the pretrained model files from Hugging Face into your local cache (~/.cache/huggingface/) and checks their SHA-256 checksums (a digital fingerprint that verifies the downloaded file is intact and uncorrupted).
Choosing a landmark model (pose_model)
pose_model="hrnet"(default, 41 MB) — lightweight and fast to download; ideal for testing on a laptop.pose_model="vitpose"(1.23 GB) — highest accuracy (0.58% median NME, ~1 pixel of error on a 200-pixel face); best for final analyses.pose_model="rtmpose"(62 MB) — fastest throughput for processing long videos on a GPU.
See the Pretrained Models Guide for full benchmarks.
Step 2: Inspect what PrimateFace found¶
pf.analyze() returns a list of Face objects sorted from highest to lowest confidence (or an empty list [] if no face is found):
face = faces[0]
print("Summary:", face)
print("Box [x1, y1, x2, y2] in pixels:", face.bbox.round(1))
print("Confidence (0 to 1):", round(face.score, 3))
print("Landmarks array shape:", face.keypoints.shape) # 68 points x (x, y, confidence)
Expected output:
Summary: Face(score=0.96, bbox=[142, 68, 418, 355], landmarks=68)
Box [x1, y1, x2, y2] in pixels: [142.3 68.1 418.4 355.2]
Confidence (0 to 1): 0.964
Landmarks array shape: (68, 3)
Each row of face.keypoints holds (x, y, confidence) for one of the 68 anatomical landmarks (jawline 0–16, eyebrows 17–26, nose 27–35, eyes 36–47, outer and inner lips 48–67).
Step 3: Measure biological features (no geometry math required)¶
Every Face object computes ethology-ready measurements on demand—you don't need to write trigonometry or pixel-distance code yourself:
yaw, pitch, roll = face.head_pose
print(f"Head orientation (deg): yaw={yaw:.1f}, pitch={pitch:.1f}, roll={roll:.1f}")
print(f"Mouth aperture (IOD-normalized): {face.mouth_aperture:.3f}")
print(f"Eye aperture (right, left): {tuple(round(v, 3) for v in face.eye_aperture)}")
print(f"Brow position (right, left): {tuple(round(v, 3) for v in face.brow_position)}")
print(f"Facial asymmetry (0 = symmetric): {face.symmetry:.4f}")
print(f"Image quality summary: { {k: round(v, 2) for k, v in face.quality.items()} }")
Expected output:
Head orientation (deg): yaw=4.8, pitch=-2.3, roll=1.1
Mouth aperture (IOD-normalized): 0.084
Eye aperture (right, left): (0.142, 0.138)
Brow position (right, left): (0.312, 0.305)
Facial asymmetry (0 = symmetric): 0.0312
Image quality summary: {'blur': 412.5, 'size': 0.18, 'visibility': 1.0, 'brightness': 118.4, 'score': 0.91}
- Head orientation (
head_pose):yaw= turning head left/right,pitch= tilting chin up/down,roll= tilting head toward either shoulder (all in degrees). - Why normalize by interocular distance (IOD)? Raw pixel distances shrink whenever an animal steps away from the camera. Dividing distances by each frame's eye-center-to-eye-center distance (
face.interocular_distance) makes mouth opening, eye opening, and brow height directly comparable across zoom levels, camera distances, and individuals. - Full kinematic dictionary:
face.kinematicsreturns all 14 geometric measurements in one dictionary (includingmouth_width,mouth_aspect_ratio,face_height,face_width,face_aspect_ratio,jaw_width,nose_length, andeye_to_mouth). - Quality filtering (
face.quality): Useface.quality["score"](0 to 1) orblur(higher = sharper; >500 is crisp) andvisibilityto automatically drop blurry or occluded frames before statistical analysis.
Step 4: Save an annotated image¶
Visualizing a handful of frames is the fastest way to verify landmark placement on your species:
# Draw bounding box + 68 landmarks + facial contour lines
primateface.PrimateFace.draw(faces, "demos/ateles_000003.jpeg", output="landmarks.jpg")
# Or draw a clean 3D head-orientation wireframe cube + axes
primateface.PrimateFace.draw(faces, "demos/ateles_000003.jpeg", output="head_pose.jpg", show_pose=True)
(Setting show_pose=True hides the bounding box and landmark dots by default so the 3D head-orientation cube is easy to inspect.)
Step 5: Export to a spreadsheet or pose toolkit¶
Export the detected face—including all 68 landmark coordinates, kinematics, head pose, symmetry, and quality scores—directly to a file format your downstream workflow reads:
# Spreadsheet for Excel, R, or pandas
primateface.io.to_csv(faces, "results.csv", image_path="demos/ateles_000003.jpeg")
# Standard computer-vision annotation format (COCO JSON)
primateface.io.to_coco_json(faces, "results_coco.json", image_path="demos/ateles_000003.jpeg")
# DeepLabCut / Lightning Pose MultiIndex CSV (3-row header spreadsheet used by DeepLabCut & Lightning Pose)
primateface.io.to_dlc_csv(faces, "results_dlc.csv")
# SLEAP (.slp) and Neurodata Without Borders (.nwb) — requires: uv pip install -e ".[interop]"
primateface.io.to_sleap(faces, "results.slp")
primateface.io.to_nwb(faces, "results.nwb")
Prefer the command line?¶
If you want to run PrimateFace on one photo or a whole folder without writing a Python script, use the built-in primateface CLI (command-line interface):
Expected output:
Processes every .jpg, .jpeg, .png, .bmp, .tiff, and .webp image in ./photos/ and saves annotated copies (viz_<filename>) into ./annotated/.
For video files, use the demo video CLI (after downloading local weights with python demos/download_models.py ./models) or loop over frames directly in Python:
python demos/primateface_demo.py process \
--input my_video.mp4 --input-type video \
--det-checkpoint ./models/primateface_rfdetr_m_v1.0.0.pth \
--pose-config ./models/mmpose_config.py \
--pose-checkpoint ./models/mmpose_checkpoint.pth \
--output-dir results/ --save-viz --viz-pose --smooth
Or analyze frames directly in Python with OpenCV (cv2):
Technical details: All CLI options
primateface analyze supports --det-model {rfdetr,cascade_rcnn}, --pose-model {hrnet,rtmpose,vitpose}, --det-threshold 0.5, --device {cuda:0,cpu}, and --model-dir /path/to/weights (to reuse local weights offline).
Next steps¶
- Important before publishing: Read Scope & Intended Use to see what PrimateFace is validated for—and what it explicitly does not claim.
- Compare accuracy, speed, and licenses across all 9 checkpoints in Pretrained Models.
- Dive deeper into time-series kinematics, smoothing, and export formats in Analysis & Data Export.