如何自动化Stable Diffusion的Inpainting流程实现自动换衣?
实现Stable Diffusion Inpainting自动化(衣物替换场景)
一、自动识别衣物区域
要实现全程自动化,第一步是无需手动绘制掩码,精准定位照片中的衣物区域。目前常用两种方案:
- 通用分割模型:比如Segment Anything Model (SAM),可通过自动检测生成衣物掩码。调用其Python接口,就能快速获取目标区域的高精度掩码。
- 专用衣物分割模型:比如基于HRNet的人体衣物分割模型,这类模型针对上衣、裤子、裙子等类别做了专项优化,能直接输出对应衣物的掩码,精度更适配场景。
示例代码(SAM生成衣物掩码):
from segment_anything import sam_model_registry, SamAutomaticMaskGenerator import cv2 import torch # 加载SAM模型 sam_checkpoint = "sam_vit_h_4b8939.pth" model_type = "vit_h" device = "cuda" if torch.cuda.is_available() else "cpu" sam = sam_model_registry[model_type](checkpoint=sam_checkpoint) sam.to(device=device) # 生成自动掩码 mask_generator = SamAutomaticMaskGenerator(sam) image = cv2.imread("person_photo.jpg") image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) masks = mask_generator.generate(image) # 筛选衣物掩码(根据位置、面积等条件调整逻辑) clothing_mask = None for mask in masks: # 示例:筛选躯干区域、面积符合的掩码 if mask['bbox'][1] < image.shape[0]*0.7 and mask['area'] > 10000: clothing_mask = mask['segmentation'] break
二、Inpainting流程自动化
无需依赖Web UI,直接用Hugging Face的diffusers库即可实现Stable Diffusion Inpainting的控制台调用,步骤如下:
- 加载Stable Diffusion Inpaint流水线
- 传入原始图片、衣物掩码、替换衣物的提示词
- 生成并保存结果图
示例代码:
from diffusers import StableDiffusionInpaintPipeline import numpy as np # 加载Inpaint流水线 pipe = StableDiffusionInpaintPipeline.from_pretrained( "runwayml/stable-diffusion-inpainting", torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32 ).to(device) # 适配模型要求的掩码格式 clothing_mask = np.array(clothing_mask, dtype=np.uint8) * 255 clothing_mask = cv2.resize(clothing_mask, (512, 512)) resized_image = cv2.resize(image, (512, 512)) # 生成替换后的图片 prompt = "a person wearing a black leather jacket, high resolution, realistic" negative_prompt = "blurry, distorted, ugly" result = pipe( prompt=prompt, image=resized_image, mask_image=clothing_mask, strength=0.8, guidance_scale=7.5 ).images[0] result.save("clothing_replaced.jpg")
三、控制台应用封装
用argparse库处理命令行参数,把上述逻辑整合成可直接运行的控制台程序:
import argparse def main(): parser = argparse.ArgumentParser(description="Stable Diffusion Clothing Replacement Tool") parser.add_argument("--input", required=True, help="Path to input person photo") parser.add_argument("--output", required=True, help="Path to save output image") parser.add_argument("--prompt", required=True, help="Prompt describing the new clothing") args = parser.parse_args() # 整合SAM掩码生成与Inpainting逻辑(复用前面的代码片段) # 读取输入图片 image = cv2.imread(args.input) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # 生成衣物掩码(SAM部分代码) # ... # 执行Inpainting(diffusers部分代码) # ... # 保存结果 result.save(args.output) if __name__ == "__main__": main()
运行示例:
python clothing_replacer.py --input person.jpg --output result.jpg --prompt "a person wearing a casual denim shirt"
注意事项:
- 提前安装依赖:
pip install segment-anything diffusers torch opencv-python argparse - SAM权重文件需提前下载或让代码自动拉取
- 可根据效果调整掩码筛选逻辑、Inpainting的
strength和guidance_scale参数
内容的提问来源于stack exchange,提问作者jens schmitz
相关产品推荐
相关产品推荐

