face parsing

提供商jonathandinu
分类image-segmentation
许可证Apache-2.0
下载量151.4K
星标0

简介

Face Parsing 是一款专注于人脸语义分割的图像处理模型。它能将人脸图像中的不同区域(如眼睛、眉毛、嘴唇、皮肤等)进行像素级的精准拆分和标注。对于开发者而言,它解决了人脸分析中“粗粒度”到“细粒度”的跨越,非常适合用于美颜相机特效、虚拟试妆、数字人驱动以及人脸特征分析等场景。该模型上手难度较低,通常作为图像预处理管线的一环,可与 OpenCV 或 PyTorch 等主流框架无缝衔接,为后续的图像编辑或分析提供精确的掩码(Mask)支撑。

核心亮点

  • 像素级人脸区域拆分,支持精细化掩码提取
  • 适配美颜、试妆等虚拟增强视觉场景
  • Apache-2.0 协议,商业化集成门槛低
  • 可作为数字人驱动的底层特征分析工具

使用方法

安装依赖
# 安装 Hugging Face transformers
pip install transformers torch
SDK 使用
# 使用 transformers 加载模型
from transformers import AutoModel, AutoTokenizer

model = AutoModel.from_pretrained("jonathandinu/face-parsing")
tokenizer = AutoTokenizer.from_pretrained("jonathandinu/face-parsing")

Hugging Face 下载

我们推荐使用命令行或者 Hugging Face Hub SDK 来进行模型的下载。

操作指引:在下载前,请先通过如下命令安装 huggingface_hub:

操作指引
pip install -U huggingface_hub

命令行下载

下载完整模型库

下载完整模型库
huggingface-cli download jonathandinu/face-parsing

下载单个文件到指定本地文件夹(以下载 config.json 到当前路径下 ./dir 目录为例)

下载单个文件到指定本地文件夹(以下载 config.json 到当前路径下 ./dir 目录为例)
huggingface-cli download jonathandinu/face-parsing config.json --local-dir ./dir

更多命令行下载选项,可参见官方文档

SDK 下载

SDK 下载
# 模型下载
from huggingface_hub import snapshot_download
model_dir = snapshot_download('jonathandinu/face-parsing')

Git 下载

请确保 lfs 已经被正确安装

Git 下载
git lfs install
git clone https://huggingface.co/jonathandinu/face-parsing

如果您希望跳过 lfs 大文件下载,可以使用如下命令

跳过 LFS
GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/jonathandinu/face-parsing

模型文件托管在 Hugging Face Hub,使用 HF CLI / SDK / Git 直接下载,不经过本站。

PyTorch / Transformers 使用

安装 Transformers

安装 Transformers
pip install -U transformers torch

模型加载和推理

模型加载和推理
from transformers import AutoModelForCausalLM, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained('jonathandinu/face-parsing')
tokenizer = AutoTokenizer.from_pretrained('jonathandinu/face-parsing')

完整文档

来源: HuggingFace

---
language: en
library_name: transformers
tags:
- vision
- image-segmentation
- nvidia/mit-b5
- transformers.js
- onnx
datasets:
- celebamaskhq
---

Face Parsing

!example image and output

Semantic segmentation model fine-tuned from nvidia/mit-b5 with CelebAMask-HQ for face parsing. For additional options, see the Transformers Segformer docs.

> ONNX model for web inference contributed by Xenova.

Usage in Python

Exhaustive list of labels can be extracted from config.json.

| id | label | note |
| :-: | :--------- | :---------------- |
| 0 | background | |
| 1 | skin | |
| 2 | nose | |
| 3 | eye_g | eyeglasses |
| 4 | l_eye | left eye |
| 5 | r_eye | right eye |
| 6 | l_brow | left eyebrow |
| 7 | r_brow | right eyebrow |
| 8 | l_ear | left ear |
| 9 | r_ear | right ear |
| 10 | mouth | area between lips |
| 11 | u_lip | upper lip |
| 12 | l_lip | lower lip |
| 13 | hair | |
| 14 | hat | |
| 15 | ear_r | earring |
| 16 | neck_l | necklace |
| 17 | neck | |
| 18 | cloth | clothing |

python
import torch
from torch import nn
from transformers import SegformerImageProcessor, SegformerForSemanticSegmentation

from PIL import Image
import matplotlib.pyplot as plt
import requests

convenience expression for automatically determining device

device = ( "cuda" # Device for NVIDIA or AMD GPUs if torch.cuda.is_available() else "mps" # Device for Apple Silicon (Metal Performance Shaders) if torch.backends.mps.is_available() else "cpu" )

load models

image_processor = SegformerImageProcessor.from_pretrained("jonathandinu/face-parsing") model = SegformerForSemanticSegmentation.from_pretrained("jonathandinu/face-parsing") model.to(device)

expects a PIL.Image or torch.Tensor

url = "https://images.unsplash.com/photo-1539571696357-5a69c17a67c6" image = Image.open(requests.get(url, stream=True).raw)

run inference on image

inputs = image_processor(images=image, return_tensors="pt").to(device) outputs = model(inputs) logits = outputs.logits # shape (batch_size, num_labels, ~height/4, ~width/4)

resize output to match input image dimensions

upsampled_logits = nn.functional.interpolate(logits, size=image.size[::-1], # H x W mode='bilinear', align_corners=False)

get label masks

labels = upsampled_logits.argmax(dim=1)[0]

move to CPU to visualize in matplotlib

labels_viz = labels.cpu().numpy() plt.imshow(labels_viz) plt.show()

Usage in the browser (Transformers.js)

js
import {
  pipeline,
  env,
} from "https://cdn.jsdelivr.net/npm/@xenova/[email protected]";

// important to prevent errors since the model files are likely remote on HF hub
env.allowLocalModels = false;

// instantiate image segmentation pipeline with pretrained face parsing model
model = await pipeline("image-segmentation", "jonathandinu/face-parsing");

// async inference since it could take a few seconds
const output = await model(url);

// each label is a separate mask object
// [
// { score: null, label: 'background', mask: transformers.js RawImage { ... }}
// { score: null, label: 'hair', mask: transformers.js RawImage { ... }}
// ...
// ]
for (const m of output) {
print(Found ${m.label});
m.mask.save(${m.label}.png);
}

p5.js

Since p5.js uses an animation loop abstraction, we need to take care loading the model and making predictions.

js
// ...

// asynchronously load transformers.js and instantiate model
async function preload() {
// load transformers.js library with a dynamic import
const { pipeline, env } = await import(
"https://cdn.jsdelivr.net/npm/@xenova/[email protected]"
);

// important to prevent errors since the model files are remote on HF hub
env.allowLocalModels = false;

// instantiate image segmentation pipeline with pretrained face parsing model
model = await pipeline("image-segmentation", "jonathandinu/face-parsing");

print("face-parsing model loaded");
}

// ...

full p5.js example

Model Description

  • Model type: Transformer-based semantic segmentation image model
  • License: non-commercial research and educational purposes

Limitations and Bias

Bias

While the capabilities of computer vision models are impressive, they can also reinforce or exacerbate social biases. The CelebAMask-HQ dataset used for fine-tuning is large but not necessarily perfectly diverse or representative. Also, they are images of.... just celebrities.