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.

7.2 KB
Raw Blame
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Portrait Matting with MODNet\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/13_portrait_matting.ipynb) [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/portrait-matting-with-modnet)\n",
    "\n",
    "MODNet produces a soft alpha matte from a full image. It is trimap-free, so it needs no face detection and no cropping.\n",
    "\n",
    "<img src=\"https://raw.githubusercontent.com/yakhyo/uniface/main/assets/demo/matting.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",
    "\n",
    "import uniface\n",
    "from uniface.matting import MODNet\n",
    "\n",
    "print(f\"UniFace version: {uniface.__version__}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "MODNet has two variants:\n",
    "- **PHOTOGRAPHIC** (default): optimized for high-quality portrait photos\n",
    "- **WEBCAM**: optimized for real-time webcam feeds\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "matting = MODNet()\n",
    "\n",
    "print(f\"Input size: {matting.input_size}\")\n",
    "print(f\"Input name: {matting.input_name}\")\n",
    "print(f\"Output names: {matting.output_names}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Helper Functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def compose(image, matte, background=None):\n",
    "    \"\"\"Composite foreground over a background using the alpha matte.\"\"\"\n",
    "    h, w = image.shape[:2]\n",
    "    matte_3ch = matte[:, :, np.newaxis]\n",
    "\n",
    "    if background is None:\n",
    "        bg = np.full_like(image, (0, 177, 64), dtype=np.uint8)\n",
    "    else:\n",
    "        bg = cv2.resize(background, (w, h), interpolation=cv2.INTER_AREA)\n",
    "\n",
    "    return (image * matte_3ch + bg * (1 - matte_3ch)).astype(np.uint8)\n",
    "\n",
    "\n",
    "def show_results(image, matte):\n",
    "    \"\"\"Display original, matte, and green screen as a single merged image.\"\"\"\n",
    "    matte_vis = cv2.cvtColor((matte * 255).astype(np.uint8), cv2.COLOR_GRAY2BGR)\n",
    "    green = compose(image, matte)\n",
    "    merged = np.hstack([image, matte_vis, green])\n",
    "\n",
    "    plt.figure(figsize=(18, 6))\n",
    "    plt.imshow(cv2.cvtColor(merged, cv2.COLOR_BGR2RGB))\n",
    "    plt.axis(\"off\")\n",
    "    plt.tight_layout()\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Basic Matting"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread(\"../assets/source/matte_face.jpg\")\n",
    "print(f\"Image shape: {image.shape}\")\n",
    "\n",
    "matte = matting.predict(image)\n",
    "print(f\"Matte shape: {matte.shape}\")\n",
    "print(f\"Matte dtype: {matte.dtype}\")\n",
    "print(f\"Matte range: [{matte.min():.3f}, {matte.max():.3f}]\")\n",
    "\n",
    "show_results(image, matte)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Transparent Background (RGBA)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "alpha = (matte * 255).astype(np.uint8)\n",
    "rgba = cv2.cvtColor(image, cv2.COLOR_BGR2BGRA)\n",
    "rgba[:, :, 3] = alpha\n",
    "\n",
    "# Checkerboard background to visualize transparency\n",
    "h, w = image.shape[:2]\n",
    "checker = np.zeros((h, w, 3), dtype=np.uint8)\n",
    "block = 20\n",
    "for y in range(0, h, block):\n",
    "    for x in range(0, w, block):\n",
    "        if (y // block + x // block) % 2 == 0:\n",
    "            checker[y:y+block, x:x+block] = 200\n",
    "        else:\n",
    "            checker[y:y+block, x:x+block] = 255\n",
    "\n",
    "matte_3ch = matte[:, :, np.newaxis]\n",
    "rgba_vis = (image * matte_3ch + checker * (1 - matte_3ch)).astype(np.uint8)\n",
    "\n",
    "merged = np.hstack([image, rgba_vis])\n",
    "\n",
    "plt.figure(figsize=(16, 5))\n",
    "plt.imshow(cv2.cvtColor(merged, cv2.COLOR_BGR2RGB))\n",
    "plt.axis(\"off\")\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "\n",
    "print(f\"RGBA shape: {rgba.shape}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Custom Background"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create a gradient background\n",
    "h, w = image.shape[:2]\n",
    "gradient = np.zeros((h, w, 3), dtype=np.uint8)\n",
    "for y in range(h):\n",
    "    ratio = y / h\n",
    "    gradient[y, :] = [int(180 * (1 - ratio)), int(100 + 80 * ratio), int(220 * ratio)]\n",
    "\n",
    "custom_bg = compose(image, matte, gradient)\n",
    "green_bg = compose(image, matte)\n",
    "\n",
    "merged = np.hstack([image, green_bg, custom_bg])\n",
    "\n",
    "plt.figure(figsize=(18, 6))\n",
    "plt.imshow(cv2.cvtColor(merged, cv2.COLOR_BGR2RGB))\n",
    "plt.axis(\"off\")\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Notes\n",
    "\n",
    "- MODNet runs on the whole image and needs no detector.\n",
    "- A sharp, high-contrast background is the hard case, and it shows up as a faint halo along the\n",
    "  shoulders. A plain background gives a clean edge."
   ]
  }
 ],
 "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
}