Skip to content

UniFace: A Unified Face Analysis Library for Python | Detection, alignment, landmarks, face-mesh, recognition, parsing, gaze, attributes and anti-spoofing under one API.

11.3 KB
Raw Blame
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Dense Face Mesh with UniFace\n",
    "\n",
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/15_face_mesh.ipynb) [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/dense-face-mesh-with-uniface)\n",
    "\n",
    "MediaPipe Face Mesh fits 468 dense 3D landmarks to a face, or 478 with the irises.\n",
    "Unlike the other landmark models it returns **three** coordinates per point and a face-presence score, and it runs every face in an image through a **single batched inference call**.\n",
    "\n",
    "<img src=\"https://raw.githubusercontent.com/yakhyo/uniface/main/assets/demo/face_mesh.jpg\" width=\"100%\">\n",
    "\n",
    "---\n",
    "\n",
    "**UniFace** is a lightweight, production-ready Python library for face detection, recognition, tracking, landmark analysis, face parsing, gaze estimation, and face attributes.\n",
    "\n",
    "GitHub: [github.com/yakhyo/uniface](https://github.com/yakhyo/uniface) | Docs: [yakhyo.github.io/uniface](https://yakhyo.github.io/uniface)\n",
    "\n",
    "## Setup\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install -q \"uniface[cpu]\"\n",
    "\n",
    "# Clone repo for assets (Colab / Kaggle only)\n",
    "import os\n",
    "if any(k in os.environ for k in ('COLAB_GPU', 'COLAB_RELEASE_TAG', 'KAGGLE_KERNEL_RUN_TYPE')):\n",
    "    if not os.path.exists('uniface'):\n",
    "        !git clone --depth 1 https://github.com/yakhyo/uniface.git\n",
    "    os.chdir('uniface/examples')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "from pathlib import Path\n",
    "\n",
    "import uniface\n",
    "from uniface.detection import SCRFD, BlazeFace\n",
    "from uniface.draw import draw_mesh\n",
    "from uniface.landmark import FaceMesh\n",
    "\n",
    "print(f\"UniFace version: {uniface.__version__}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Any detector works — Face Mesh only needs a box plus the two eye points\n",
    "detector = SCRFD()\n",
    "mesher = FaceMesh()\n",
    "\n",
    "print(f\"Landmarks: {mesher.num_landmarks}\")\n",
    "print(f\"Input size: {mesher.input_size}x{mesher.input_size}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Detect and Mesh\n",
    "\n",
    "Face Mesh needs a bounding box plus the first two landmarks (the eyes), which it uses to rotate the crop so the eye line is horizontal. Passing `Face` objects does this automatically."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread('../assets/source/mesh_face.jpg')\n",
    "\n",
    "faces = detector.detect(image)\n",
    "print(f\"Detected {len(faces)} face(s)\")\n",
    "\n",
    "# One batched call for every face in the image\n",
    "results = mesher.predict(image, faces)\n",
    "\n",
    "result = results[0]\n",
    "print(f\"Landmarks shape: {result.landmarks.shape}\")   # (468, 3)\n",
    "print(f\"2D only: {result.points_2d.shape}\")   # (468, 2)\n",
    "print(f\"Presence score: {result.score:.4f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Visualize\n",
    "\n",
    "`draw_mesh` has three render modes. `full` draws the dense 2556-edge tessellation, the most detailed but noticeably slower. Prefer `partial` or `points` for video."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
    "\n",
    "for ax, mode in zip(axes, ['points', 'partial', 'full']):\n",
    "    canvas = image.copy()\n",
    "    draw_mesh(canvas, result.landmarks, mode=mode)\n",
    "    ax.imshow(cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB))\n",
    "    ax.set_title(f\"mode='{mode}'\")\n",
    "    ax.axis('off')\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. The Depth Coordinate\n",
    "\n",
    "`z` is **relative** depth on the same pixel scale as `x`/`y`, where smaller is closer to the camera. It has no absolute origin, so it is only meaningful *within* one face, not between faces or between images."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "points = result.landmarks\n",
    "\n",
    "plt.figure(figsize=(7, 7))\n",
    "scatter = plt.scatter(points[:, 0], points[:, 1], c=points[:, 2], cmap='viridis', s=8)\n",
    "plt.colorbar(scatter, label='z (relative depth, smaller = closer)')\n",
    "plt.gca().invert_yaxis()\n",
    "plt.gca().set_aspect('equal')\n",
    "plt.title('468 landmarks coloured by depth')\n",
    "plt.show()\n",
    "\n",
    "print(f\"z range: {points[:, 2].min():.1f} .. {points[:, 2].max():.1f}\")\n",
    "print(\"The nose tip is the closest point; the ears and jaw edges sit furthest back.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. The 478-Point Variant: Irises\n",
    "\n",
    "`V2_478` returns the same 468 mesh points in the same order, plus ten iris points. Switching\n",
    "is a one-word change, and region membership lives in named constants rather than magic indices."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from uniface.constants import FaceMeshWeights\n",
    "from uniface.landmark import IRIS_LEFT, IRIS_RIGHT, NUM_MESH_LANDMARKS\n",
    "\n",
    "iris_mesher = FaceMesh(model_name=FaceMeshWeights.V2_478)\n",
    "iris_result = iris_mesher.predict(image, faces)[0]\n",
    "\n",
    "print(f\"landmarks: {iris_result.landmarks.shape}\")\n",
    "print(f\"the first {NUM_MESH_LANDMARKS} are exactly what V1_468 returns\")\n",
    "print(f\"left iris: {iris_result.landmarks[IRIS_LEFT].shape} (centre, right, top, left, bottom)\")\n",
    "print(f\"right iris: {iris_result.landmarks[IRIS_RIGHT].shape}\")\n",
    "\n",
    "left_pupil = iris_result.landmarks[IRIS_LEFT][0, :2]\n",
    "print(f\"left pupil at: ({left_pupil[0]:.0f}, {left_pupil[1]:.0f})\")\n",
    "\n",
    "# Each iris is centre-first, so the mean distance from point 0 to the other four is its radius.\n",
    "# A human iris is close to 11.7 mm across whoever you measure, which turns that radius into\n",
    "# a real-world scale reference.\n",
    "iris = iris_result.landmarks[IRIS_LEFT]\n",
    "radius_px = np.mean(np.linalg.norm(iris[1:, :2] - iris[0, :2], axis=1))\n",
    "print(f\"iris radius: {radius_px:.1f} px -> {11.7 / (2 * radius_px):.4f} mm per pixel\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, axes = plt.subplots(1, 2, figsize=(14, 7))\n",
    "\n",
    "for ax, (res, title) in zip(axes, [(result, f\"V1_468 - {len(result.landmarks)} points\"),\n",
    "                                   (iris_result, f\"V2_478 - {len(iris_result.landmarks)} points\")]):\n",
    "    canvas = image.copy()\n",
    "    draw_mesh(canvas, res.landmarks, mode=\"partial\")\n",
    "    # mark the ten iris points in red, so the difference is visible\n",
    "    if len(res.landmarks) > NUM_MESH_LANDMARKS:\n",
    "        # IRIS_LEFT / IRIS_RIGHT are slices, so index with them and iterate the points\n",
    "        iris_points = np.vstack([res.landmarks[IRIS_LEFT], res.landmarks[IRIS_RIGHT]])\n",
    "        for x, y in iris_points[:, :2]:\n",
    "            cv2.circle(canvas, (int(x), int(y)), 4, (0, 0, 255), -1)\n",
    "    ax.imshow(cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB))\n",
    "    ax.set_title(title, fontsize=13)\n",
    "    ax.axis(\"off\")\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. MediaPipe Parity\n",
    "\n",
    "Seeding the mesh with **BlazeFace** reproduces MediaPipe's own pipeline exactly.\n",
    "\n",
    "> ⚠️ BlazeFace returns **6** MediaPipe keypoints whose 4th point is a mouth *center*, not corners, so they cannot be fitted to the 5-point alignment template. It declares this with `supports_alignment = False`, and `FaceAnalyzer` disables recognition for it rather than producing broken embeddings."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# MediaPipe runs BlazeFace ahead of Face Mesh in its own pipeline\n",
    "blazeface = BlazeFace()\n",
    "\n",
    "bf_faces = blazeface.detect(image)\n",
    "bf_results = mesher.predict(image, bf_faces)\n",
    "\n",
    "print(f\"BlazeFace keypoints: {bf_faces[0].landmarks.shape}\")       # (6, 2), not (5, 2)\n",
    "print(f\"supports_alignment: {blazeface.supports_alignment}\")      # False\n",
    "\n",
    "canvas = image.copy()\n",
    "draw_mesh(canvas, bf_results[0].landmarks, mode='full')\n",
    "\n",
    "plt.figure(figsize=(7, 7))\n",
    "plt.imshow(cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB))\n",
    "plt.title('MediaPipe parity: BlazeFace + Face Mesh')\n",
    "plt.axis('off')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Other Ways to Call It"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Face Mesh implements the same interface as Landmark106 and PIPNet\n",
    "landmarks_2d = mesher.get_landmarks(image, faces[0].bbox)\n",
    "print(f\"get_landmarks: {landmarks_2d.shape}\")\n",
    "\n",
    "# Without a detector, pass boxes directly\n",
    "x1, y1, x2, y2 = faces[0].bbox\n",
    "manual = mesher.predict(image, bboxes=[[x1, y1, x2, y2]])\n",
    "print(f\"From a raw box: {manual[0].landmarks.shape}\")\n",
    "\n",
    "# Tune the crop with margin= if the mesh clips on unusual framing\n",
    "tight = mesher.predict(image, faces, margin=0.1)[0]\n",
    "print(f\"Tighter crop shifts the fit: {not np.allclose(tight.landmarks, result.landmarks)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Notes\n",
    "\n",
    "- `z` is a relative depth on the same scale as `x` and `y`, not a distance in millimetres.\n",
    "- The presence score saturates near 1.0, so it tells you the model ran rather than how well the\n",
    "  mesh fits.\n",
    "- `IRIS_LEFT` and `IRIS_RIGHT` are slices, not index lists. Index the array with them.\n",
    "- Face Mesh and BlazeFace weights come from Google MediaPipe and are Apache-2.0 licensed."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}