UniFace: A Unified Face Analysis Library for Python | Detection, alignment, landmarks, face-mesh, recognition, parsing, gaze, attributes and anti-spoofing under one API.
Python computer-visiondeep-learningface-alignmentface-analysisface-anonymizationface-anti-spoofingface-attributesface-detectionface-meshface-parsingface-quality-assessmentface-recognitionface-segmentationface-trackingfacial-landmarksgaze-estimationhead-pose-estimationonnxruntimeportrait-mattingpython
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Face Parsing with UniFace\n",
"\n",
"[](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/06_face_parsing.ipynb) [](https://www.kaggle.com/code/yakhyokhuja/face-parsing-with-uniface)\n",
"\n",
"Label every pixel of a face as skin, eyes, nose, mouth, hair and so on, using BiSeNet.\n",
"Face parsing segments a face image into different facial components such as skin, eyes, nose, mouth, hair, etc.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/yakhyo/uniface/main/assets/demo/parsing.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 numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from pathlib import Path\n",
"\n",
"import uniface\n",
"from uniface.detection import SCRFD\n",
"from uniface.parsing import BiSeNet\n",
"from uniface.constants import ParsingWeights\n",
"from uniface.draw import vis_parsing_maps\n",
"\n",
"print(f\"UniFace version: {uniface.__version__}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Initialize face parser (uses ResNet18 by default)\n",
"parser = BiSeNet(model_name=ParsingWeights.RESNET34) # use resnet34 for better accuracy\n",
"detector = SCRFD()\n",
"\n",
"\n",
"def face_crop(image, margin=0.6, size=512):\n",
" \"\"\"Square crop centred on the largest face.\n",
"\n",
" BiSeNet is trained on CelebAMask-HQ, which is face-centred crops, so a full-body\n",
" portrait leaves the face too small once the image is resized for inference. Cropping\n",
" first is what makes the fine classes (eyes, brows, lips) come out cleanly.\n",
" \"\"\"\n",
" faces = detector.detect(image)\n",
" if not faces:\n",
" return image\n",
" face = max(faces, key=lambda f: f.bbox[2] - f.bbox[0])\n",
" x1, y1, x2, y2 = face.bbox\n",
" cx, cy = (x1 + x2) / 2, (y1 + y2) / 2\n",
" h, w = image.shape[:2]\n",
" half = min(max(x2 - x1, y2 - y1) * (1 + margin) / 2, w / 2, h / 2)\n",
" cx = min(max(cx, half), w - half)\n",
" cy = min(max(cy, half), h - half)\n",
" crop = image[int(cy - half):int(cy + half), int(cx - half):int(cx + half)]\n",
" return cv2.resize(crop, (size, size), interpolation=cv2.INTER_CUBIC)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. Face Parsing Classes\n",
"\n",
"The BiSeNet model segments faces into **19 different classes**:\n",
"\n",
"| Class ID | Component | Class ID | Component |\n",
"|----------|-----------|----------|----------|\n",
"| 0 | Background | 10 | Nose |\n",
"| 1 | Skin | 11 | Mouth |\n",
"| 2 | Left Eyebrow | 12 | Upper Lip |\n",
"| 3 | Right Eyebrow | 13 | Lower Lip |\n",
"| 4 | Left Eye | 14 | Neck |\n",
"| 5 | Right Eye | 15 | Neck Lace |\n",
"| 6 | Eye Glasses | 16 | Cloth |\n",
"| 7 | Left Ear | 17 | Hair |\n",
"| 8 | Right Ear | 18 | Hat |\n",
"| 9 | Ear Ring | | |"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. Process Test Images\n",
"\n",
"The test images are already cropped face images, so we can directly parse them without face detection."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Get all test images\n",
"demo_dir = Path('../assets/source')\n",
"demo_images = [demo_dir / n for n in ('parse_face.jpg', 'mesh_face.jpg', 'age_adult.jpg')]\n",
"\n",
"# Store original and processed images\n",
"original_images = []\n",
"parsed_images = []\n",
"\n",
"for image_path in demo_images:\n",
" print(f\"Processing: {image_path.name}\")\n",
"\n",
" # Load the photo, then crop to the face before parsing\n",
" image = face_crop(cv2.imread(str(image_path)))\n",
"\n",
" mask = parser.parse(image)\n",
" unique_classes = len(set(mask.flatten()))\n",
" print(f' Parsed with {unique_classes} unique classes')\n",
"\n",
" # Visualize the parsing result\n",
" image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n",
" vis_result = vis_parsing_maps(image_rgb, mask, save_image=False)\n",
"\n",
" original_images.append(image_rgb)\n",
" parsed_images.append(vis_result)\n",
"\n",
"print(f\"\\nProcessed {len(demo_images)} images\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. Visualize Results\n",
"\n",
"Display original images in the first row and parsed images in the second row."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"num_images = len(original_images)\n",
"fig, axes = plt.subplots(2, num_images, figsize=(4 * num_images, 8))\n",
"\n",
"if num_images == 1:\n",
" axes = axes.reshape(-1, 1)\n",
"\n",
"for i in range(num_images):\n",
" # Original image\n",
" axes[0, i].imshow(original_images[i])\n",
" axes[0, i].set_title(f'Original {i+1}', fontsize=12)\n",
" axes[0, i].axis('off')\n",
"\n",
" # Parsed image\n",
" axes[1, i].imshow(parsed_images[i])\n",
" axes[1, i].set_title(f'Parsed {i+1}', fontsize=12)\n",
" axes[1, i].axis('off')\n",
"\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4. Parse a Single Face (Detailed)\n",
"\n",
"Let's parse a single face and display the segmentation mask in detail."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Load a test image\n",
"image_path = '../assets/source/parse_face.jpg'\n",
"image = face_crop(cv2.imread(image_path))\n",
"\n",
"# Parse the face\n",
"mask = parser.parse(image)\n",
"\n",
"# Visualize\n",
"image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n",
"vis_result = vis_parsing_maps(image_rgb, mask, save_image=False)\n",
"\n",
"# Display\n",
"fig, axes = plt.subplots(1, 3, figsize=(15, 5))\n",
"\n",
"axes[0].imshow(image_rgb)\n",
"axes[0].set_title('Original Face', fontsize=14)\n",
"axes[0].axis('off')\n",
"\n",
"axes[1].imshow(mask, cmap='tab20')\n",
"axes[1].set_title('Segmentation Mask', fontsize=14)\n",
"axes[1].axis('off')\n",
"\n",
"axes[2].imshow(vis_result)\n",
"axes[2].set_title('Overlay Visualization', fontsize=14)\n",
"axes[2].axis('off')\n",
"\n",
"plt.tight_layout()\n",
"plt.show()\n",
"\n",
"print(f\"Mask shape: {mask.shape}\")\n",
"print(f\"Unique classes: {np.unique(mask)}\")\n",
"print(f\"Number of classes: {len(np.unique(mask))}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 5. Extract Specific Facial Components\n",
"\n",
"You can extract specific facial components using the mask."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Load image\n",
"image_path = '../assets/source/parse_face.jpg'\n",
"image = face_crop(cv2.imread(image_path))\n",
"image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n",
"\n",
"# Parse the face\n",
"mask = parser.parse(image)\n",
"\n",
"# Extract specific components\n",
"# 1 = skin, 17 = hair, 10 = nose, 12 = upper lip, 13 = lower lip\n",
"components_to_extract = {\n",
" 'Skin': 1,\n",
" 'Hair': 17,\n",
" 'Nose': 10,\n",
" 'Lips': [12, 13] # Upper and lower lips combined\n",
"}\n",
"\n",
"fig, axes = plt.subplots(1, len(components_to_extract) + 1, figsize=(20, 4))\n",
"\n",
"# Show original\n",
"axes[0].imshow(image_rgb)\n",
"axes[0].set_title('Original', fontsize=12)\n",
"axes[0].axis('off')\n",
"\n",
"# Extract and show each component\n",
"for idx, (name, class_ids) in enumerate(components_to_extract.items(), 1):\n",
" # Handle both single class and multiple classes\n",
" if isinstance(class_ids, list):\n",
" component_mask = np.zeros_like(mask, dtype=np.uint8)\n",
" for class_id in class_ids:\n",
" component_mask |= (mask == class_id).astype(np.uint8)\n",
" else:\n",
" component_mask = (mask == class_ids).astype(np.uint8)\n",
"\n",
" # Apply mask to image\n",
" extracted = image_rgb.copy()\n",
" extracted[component_mask == 0] = 0\n",
"\n",
" axes[idx].imshow(extracted)\n",
" axes[idx].set_title(name, fontsize=12)\n",
" axes[idx].axis('off')\n",
"\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Notes\n",
"\n",
"- `parse()` takes the full image and needs no detector.\n",
"- The mask holds one class id per pixel, 0 being background. Use `np.isin(mask, ids)` to pull\n",
" out one part or several at once."
]
}
],
"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
}