Z-Image Face Detailer 人像精修与面部增强工作流
关键词: z-image face detailer portrait enhancement
目录
- 简介
- 人脸检测与遮罩技术
- Face Detailer v2.0 工作流概述
- 人脸修复 vs 人脸增强
- ComfyUI Face Detailer 节点与配置
- 面部分辨率增强
- 面部伪影去除
- 批量人脸处理
- 与图像修复工作流的集成
- 实用示例
- 参考资源
简介
Face Detailer(人脸精修器)是针对图像中面部区域进行自动检测和增强的专用工作流。与 ZI-037(通用放大器+细节增强器)不同,本文专注于面部特征的专门优化,包括人脸检测、面部遮罩生成、面部分辨率提升和面部瑕疵修复。
扩散模型在生成人脸时经常面临以下挑战:
- 面部不对称或变形
- 眼睛不一致(方向、大小)
- 牙齿畸形
- 面部纹理粗糙或模糊
- 多人场景中的个别面部质量问题
Face Detailer 工作流通过自动化检测和修复这些常见问题来改善输出质量。
人脸检测与遮罩技术
人脸检测器
目前主流的人脸检测器包括:
| 检测器 | 优点 | 缺点 |
|---|---|---|
| MediaPipe Face Detection | 速度快,轻量级 | 精度中等,对遮挡处理一般 |
| RetinaFace | 精度高,支持多种姿态 | 速度较慢 |
| YOLO-Face | 速度快,适合实时检测 | 对小人脸检测精度较低 |
| BlazeFace | 极快,移动端友好 | 精度最低 |
| Face Detection v2 (ComfyUI) | 专为 ComfyUI 优化 | 需要额外安装 |
人脸检测实现
import cv2
import mediapipe as mp
# MediaPipe 人脸检测
mp_face_detection = mp.solutions.face_detection.FaceDetection(
model_selection=0, # 0 = short range, 1 = full range
min_detection_confidence=0.5
)
def detect_faces(image_path):
image = cv2.imread(image_path)
rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
results = mp_face_detection.process(rgb_image)
faces = []
if results.detections:
for detection in results.detections:
bbox = detection.location_data.relative_bounding_box
h, w = image.shape[:2]
x = int(bbox.xmin * w)
y = int(bbox.ymin * h)
width = int(bbox.width * w)
height = int(bbox.height * h)
faces.append({"x": x, "y": y, "width": width, "height": height})
return faces
# 使用
faces = detect_faces("group_photo.jpg")
for i, face in enumerate(faces):
print(f"Face {i+1}: ({face['x']}, {face['y']}), {face['width']}x{face['height']}")
人脸遮罩生成
生成面部遮罩有两种主要方法:
方法一:矩形遮罩(简单快速)
import numpy as np
from PIL import Image
def create_rect_mask(face_bbox, image_size, padding=50):
"""创建带填充的矩形人脸遮罩"""
mask = np.zeros(image_size, dtype=np.uint8)
x = max(0, face_bbox["x"] - padding)
y = max(0, face_bbox["y"] - padding)
w = min(image_size[0] - x, face_bbox["width"] + 2 * padding)
h = min(image_size[1] - y, face_bbox["height"] + 2 * padding)
# 添加羽化效果
cv2.rectangle(mask, (x, y), (x + w, y + h), 255, -1)
mask = cv2.GaussianBlur(mask, (21, 21), 11)
return Image.fromarray(mask)
方法二:语义分割遮罩(更精确)
from transformers import pipeline
# 使用语义分割模型生成精确人脸遮罩
segmentor = pipeline("image-segmentation", model="facebook/detr-resnet-50-panoptic")
def create_semantic_mask(image, face_bbox):
"""使用语义分割创建精确人脸遮罩"""
results = segmentor(image)
mask = np.zeros(image.size[::-1], dtype=np.uint8)
for result in results:
if result["label"] in ["person", "face"]:
segmentation = np.array(result["mask"])
mask[segmentation > 0.5] = 255
# 裁剪到人脸区域
mask = mask[
face_bbox["y"]:face_bbox["y"] + face_bbox["height"],
face_bbox["x"]:face_bbox["x"] + face_bbox["width"]
]
return Image.fromarray(mask)
Face Detailer v2.0 工作流概述
Face Detailer v2.0 是 ComfyUI 生态系统中的人脸精修工作流,核心流程如下:
原始图像 → 人脸检测 → 裁剪人脸区域 → 放大 → 模型重绘 → 缩放回原位 → 合成回原图
核心组件
- 人脸检测器: 定位图像中所有人脸
- 区域裁剪器: 裁剪包含人脸的矩形区域(带填充)
- 放大模块: 将裁剪区域放大到目标分辨率
- 扩散模型重绘: 使用 Z-Image 对放大后的人脸进行重绘
- 缩放与融合: 将重绘结果缩放回原始大小并融合回原图
与 ZI-037 的区别
| 特性 | ZI-037 (通用放大器+细节增强器) | ZI-060 (Face Detailer) |
|---|---|---|
| 处理对象 | 整张图像 | 仅面部区域 |
| 检测模块 | 无(处理整图) | 人脸检测 + 遮罩生成 |
| 重绘范围 | 全图 | 仅面部区域 |
| 适用场景 | 整体分辨率提升 | 面部质量修复 |
| 输出 | 放大后的整图 | 原始尺寸但面部增强的图像 |
人脸修复 vs 人脸增强
人脸修复(Face Restoration)
目标: 修复损坏或畸形的面部特征
适用场景:
- 生成的面部有明显畸形(多只眼、扭曲的面部)
- 手部或面部解剖错误
- 面部纹理完全混乱
方法:
- 使用专门的修复模型(如 GFP-GAN, CodeFormer, RestoreFormer)
- 或者使用扩散模型进行高 strength 重绘(strength 0.7-0.9)
- 提示词强调正确的面部结构
提示词示例:
修复: "fix face, correct facial features, realistic face, proper anatomy"
修复: "修复面部,矫正五官,真实面部,正确解剖结构"
人脸增强(Face Enhancement)
目标: 在保持原始面部特征的基础上提升质量
适用场景:
- 面部基本正确但不够清晰
- 需要增强细节(皮肤纹理、眼睛细节)
- 提升面部分辨率
方法:
- 低 strength 重绘(strength 0.3-0.6)
- 使用超分辨率模型
- 结合修复和增强的混合方法
提示词示例:
增强: "enhance face detail, sharp eyes, natural skin texture, high quality portrait"
增强: "增强面部细节,清晰眼睛,自然皮肤纹理,高质量人像"
选择指南
| 面部问题 | 推荐方法 | Strength |
|---|---|---|
| 严重畸形 | 人脸修复 | 0.7-0.9 |
| 轻微不对称 | 人脸修复 | 0.5-0.7 |
| 模糊/低分辨率 | 人脸增强 | 0.3-0.5 |
| 需要提升细节 | 人脸增强 | 0.3-0.6 |
| 整体质量提升 | 混合方法 | 0.5-0.7 |
ComfyUI Face Detailer 节点与配置
安装必要组件
# 在 ComfyUI/custom_nodes/ 目录下安装
cd ComfyUI/custom_nodes
# Face Detailer 节点
git clone https://github.com/LucianTan/ComfyUI-FaceDetailer.git
# 或 Ultimate SD Upscale + Face Detailer
git clone https://github.com/AIGODLIKE/AI-GODLIKE-ComfyUI-Workflow.git
# 安装依赖
pip install -r ComfyUI-FaceDetailer/requirements.txt
基础 Face Detailer 工作流
{
"1": {
"class_type": "LoadImage",
"inputs": {
"image": "generated_image.jpg"
}
},
"2": {
"class_type": "FaceDetailer",
"inputs": {
"image": ["1", 0],
"model": ["model", 0],
"clip": ["clip", 0],
"vae": ["vae", 0],
"detector": "retinaface",
"face_size": 512,
"upscale_model": "4x-UltraSharp",
"upscale_by": 2.0,
"denoise": 0.5,
"cfg": 7.5,
"steps": 28,
"seed": 42
}
},
"3": {
"class_type": "SaveImage",
"inputs": {
"images": ["2", 0]
}
}
}
节点参数详解
| 参数 | 说明 | 推荐值 |
|---|---|---|
detector |
人脸检测器 | retinaface / mediapipe |
face_size |
人脸区域目标尺寸 | 384 / 512 / 768 |
upscale_model |
放大模型 | 4x-UltraSharp / RealESRGAN |
upscale_by |
放大倍数 | 1.5 - 4.0 |
denoise |
去噪强度(重绘强度) | 修复: 0.5-0.8, 增强: 0.3-0.5 |
cfg |
引导尺度 | 5.0 - 8.0 |
steps |
推理步数 | 20 - 35 |
seed |
随机种子 | 固定值确保一致 |
高级 Face Detailer 工作流
{
"1": {
"class_type": "LoadImage",
"inputs": {"image": "portrait.jpg"}
},
"2": {
"class_type": "FaceDetectionAndMasking",
"inputs": {
"image": ["1", 0],
"detector": "retinaface",
"detection_threshold": 0.5,
"bbox_expansion": 0.3
}
},
"3": {
"class_type": "CropAndUpscaleFaces",
"inputs": {
"image": ["1", 0],
"masks": ["2", 1],
"target_size": 512,
"upscale_model": "4x-UltraSharp"
}
},
"4": {
"class_type": "CLIPTextEncode",
"inputs": {
"text": "beautiful face, sharp eyes, natural skin texture, high quality portrait, detailed",
"clip": ["clip", 0]
}
},
"5": {
"class_type": "KSampler",
"inputs": {
"model": ["model", 0],
"positive": ["4", 0],
"negative": ["4_neg", 0],
"latent_image": ["3", 0],
"seed": 42,
"steps": 28,
"cfg": 7.0,
"sampler_name": "euler",
"scheduler": "normal",
"denoise": 0.5
}
},
"6": {
"class_type": "ResizeAndCompositeFaces",
"inputs": {
"original_image": ["1", 0],
"processed_faces": ["5", 0],
"masks": ["2", 1]
}
},
"7": {
"class_type": "SaveImage",
"inputs": {"images": ["6", 0]}
}
}
节点连接说明
LoadImage→ 加载需要处理的人脸图像FaceDetectionAndMasking→ 检测人脸并生成遮罩CropAndUpscaleFaces→ 裁剪并放大人脸区域CLIPTextEncode→ 编码面部增强提示词KSampler→ 使用 Z-Image 对面���进行重绘ResizeAndCompositeFaces→ 将处理后的人脸缩放并融合回原图SaveImage→ 保存最终结果
面部分辨率增强
专用面部放大模型
| 模型 | 放大倍数 | 特点 |
|---|---|---|
| 4x-UltraSharp | 4x | 通用放大,细节保留好 |
| RealESRGAN-x4plus | 4x | 面部优化,速度快 |
| GFPGAN | 4x | 专用面部修复 |
| CodeFormer | 4x | 面部修复,对低质量输入效果好 |
| RestoreFormer | 4x | 最新面部修复模型 |
面部放大工作流
低分辨率面部 → 放大模型 → 扩散模型微调 → 增强后面部
# 伪代码:面部分辨率增强流程
def enhance_face_resolution(image, face_bbox, target_size=512):
# 1. 裁剪面部区域
face_crop = crop_image(image, face_bbox)
# 2. 放大
face_upscaled = upscale(face_crop, target_size=target_size, model="4x-UltraSharp")
# 3. 扩散模型微调(低 strength)
face_enhanced = diffusion_refine(
face_upscaled,
prompt="high quality face portrait, sharp details, realistic skin texture",
strength=0.35,
steps=20,
cfg=6.0
)
# 4. 缩放回原位
face_resized = resize_to_original(face_enhanced, face_bbox)
# 5. 融合回原图
result = composite(image, face_resized, face_bbox, feather_radius=15)
return result
面部伪影去除
常见面部伪影类型
| 伪影类型 | 描述 | 修复方法 |
|---|---|---|
| 眼睛不一致 | 双眼方向或大小不同 | 高 strength 重绘 + 对称性提示词 |
| 牙齿畸形 | 牙齿形状或排列错误 | 面部修复模型 + inpainting |
| 面部扭曲 | 面部结构不对称 | 修复模型(GFP-GAN/CodeFormer) |
| 皮肤纹理异常 | 皮肤出现条纹或不自然纹理 | 低 strength 重绘 + 纹理提示词 |
| 多余面部特征 | 多余眼睛、嘴巴等 | 高 strength 重绘 + 正确解剖结构提示词 |
伪影修复工作流
{
"artifact_fix_workflow": {
"steps": [
"1. 检测面部区域",
"2. 使用修复模型进行初步修复",
"3. 使用扩散模型进行精细调整",
"4. 检查并修复特定区域(眼睛、牙齿)",
"5. 融合回原图"
],
"key_parameters": {
"restoration_model": "CodeFormer",
"restoration_weight": 0.7,
"diffusion_strength": 0.4,
"specific_fix_strength": 0.6
}
}
}
批量人脸处理
批量处理脚本
import os
import torch
from PIL import Image
from pathlib import Path
def batch_face_detailer(input_dir, output_dir, config):
"""批量人脸处理"""
os.makedirs(output_dir, exist_ok=True)
# 加载 Face Detailer 管道(假设已初始化)
# pipe = FaceDetailerPipeline(...)
for filename in os.listdir(input_dir):
if not filename.lower().endswith(('.jpg', '.jpeg', '.png')):
continue
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, filename)
try:
# 加载图像
image = Image.open(input_path)
# 检测人脸
faces = detect_faces(image)
if not faces:
print(f"No faces detected in {filename}")
continue
# 处理每个人脸
result = image
for face in faces:
result = enhance_face(result, face, config)
# 保存结果
result.save(output_path)
print(f"Processed: {filename} ({len(faces)} faces)")
except Exception as e:
print(f"Error processing {filename}: {e}")
print(f"Batch processing complete: {output_dir}")
批量配置
batch_config = {
"detector": "retinaface",
"face_size": 512,
"upscale_model": "4x-UltraSharp",
"upscale_by": 2.0,
"denoise": 0.5,
"cfg": 7.0,
"steps": 28,
"prompt": "beautiful face, sharp eyes, natural skin, high quality portrait",
"negative_prompt": "deformed, distorted, disfigured, bad anatomy, extra eyes",
"max_faces": 10, # 单图最大处理人脸数
"min_face_size": 100, # 最小人脸尺寸(像素)
"feather_radius": 15, # 遮罩羽化半径
}
与图像修复工作流的集成
面部修复 + 局部 Inpainting
对于特别复杂的面部修复,可以结合 Face Detailer 和 inpainting:
面部检测 → Face Detailer 初步修复 → 局部问题 inpainting → 最终结果
Inpainting 辅助修复
def targeted_face_fix(image, face_bbox, fix_regions):
"""
针对性面部修复
fix_regions: 需要修复的特定区域列表
"""
for region in fix_regions:
# 创建局部遮罩
mask = create_region_mask(region)
# 执行 inpainting
image = inpaint_face(
image,
mask,
prompt=get_fix_prompt(region["type"]),
strength=0.6,
steps=30,
cfg=8.0
)
return image
def get_fix_prompt(region_type):
"""获取特定区域的修复提示词"""
prompts = {
"eyes": "sharp eyes, correct eye alignment, natural eyelashes",
"mouth": "natural teeth, correct lip shape, natural smile",
"nose": "correct nose shape, proper nose bridge",
"skin": "smooth natural skin texture, no blemishes",
"ears": "correct ear shape, natural ear position",
}
return prompts.get(region_type, "natural facial features")
实用示例
示例一:人像摄影增强
场景: 提升 AI 生成的人像照片质量
工作流:
- 使用 Z-Image 生成基础人像
- Face Detailer 检测面部并增强
- 输出高清人像
提示词:
生成: "professional headshot portrait, studio lighting, neutral background,
sharp focus, photorealistic, 85mm lens"
面部增强: "beautiful face, sharp eyes, natural skin texture,
professional portrait, high quality, detailed"
参数设置:
- face_size: 512
- upscale_by: 2.0
- denoise: 0.4
- cfg: 7.0
- steps: 28
示例二:动漫角色面部修复
场景: 修复 AI 生成的动漫角色面部问题
工作流:
- 生成动漫角色
- 检测面部并裁剪
- 使用动漫风格提示词重绘
- 融合回原图
提示词:
面部修复: "beautiful anime face, large expressive eyes, smooth skin,
anime style, cel shading, detailed hair, key visual quality"
负面: "deformed face, asymmetrical eyes, extra eyes, bad anatomy,
3D render, photorealistic"
参数设置:
- face_size: 384
- upscale_by: 1.5
- denoise: 0.55
- cfg: 6.0
- steps: 25
示例三:群体照面部改善
场景: 改善多人照片中每个人脸的质量
工作流:
- 检测所有人脸
- 逐个处理每个人脸
- 保持不同人脸之间的一致性
关键点:
- 使用固定 seed 确保多人脸处理风格一致
- 对每个人脸使用相同的增强参数
- 注意人脸之间的光照一致性
# 群体照处理要点
group_photo_config = {
"detector": "retinaface",
"face_size": 512,
"denoise": 0.45, # 较低 strength 保持原有人脸特征
"cfg": 7.0,
"steps": 28,
"seed": 42, # 固定种子确保一致性
"prompt": "natural face, sharp details, consistent lighting, group photo quality",
"feather_radius": 20, # 较大羽化避免融合痕迹
}
示例四:证件照生成
场景: 使用 AI 生成符合标准的证件照
工作流:
- 生成基础人像(正面、白底)
- Face Detailer 增强面部
- 裁剪和标准化到证件照尺寸
提示词:
生成: "ID photo, front-facing portrait, plain white background,
formal attire, neutral expression, even lighting, head and shoulders"
面部增强: "clear face, sharp eyes, natural skin, ID photo quality,
professional, formal, front-facing"
尺寸标准:
- 中国身份证: 358 x 441 px (35mm x 45mm, 300dpi)
- 美国护照: 256 x 256 px (2in x 2in, 128dpi)
- 欧盟签证: 413 x 531 px (35mm x 45mm, 300dpi)
参考资源
- Z-Image Face Detailer v2.0: https://z-image.me/workflows/face-detailer
- ComfyUI-FaceDetailer: https://github.com/LucianTan/ComfyUI-FaceDetailer
- Ultimate SD Upscale + Face Detailer v3.0 (Civitai): https://civitai.com/models/ultimatesd-upscale-face-detailer
- GFP-GAN: https://github.com/TencentARC/GFPGAN
- CodeFormer: https://github.com/sczhou/CodeFormer
- MediaPipe Face Detection: https://ai.google.dev/edge/mediapipe/solutions/vision/face_detection
- Reddit 高级面部工作流: r/StableDiffusion advanced face workflows