SuperAPI AI 工具集

stable-diffusion-image-generation

设计与创作

查看项目

更新于 10-21 16:20

技能介绍

用途

该技能是一份使用 HuggingFace Diffusers 库进行 Stable Diffusion 图像生成的综合指南,面向需要构建自定义图像生成工作流的开发者与研究人员。它覆盖从文本生成图像、图像到图像转换、图像修复到图像外扩等多种任务。

主要能力

  • 文生图(Text-to-Image):根据自然语言提示生成图像。
  • 图生图(Image-to-Image):在文本引导下转换已有图像,可用于风格迁移与增强。
  • 图像修复(Inpainting):用上下文相关内容填充被遮罩区域。
  • 图像外扩(Outpainting):将图像扩展到原始边界之外。
  • 图像变体:创建已有图像的变体。
  • ControlNet:添加空间条件控制(边缘、姿态、深度)。
  • LoRA 支持:高效微调与风格适配,可加载多个 LoRA 并分别设置权重。
  • 多模型支持:SD 1.5、SDXL、SD 3.0、Flux。
  • 调度器切换:如 EulerDiscreteScheduler、DPMSolverMultistepScheduler、LCMScheduler 等,用于平衡速度与质量。
  • 显存优化:模型 CPU 卸载、顺序 CPU 卸载、注意力切片、xFormers 高效注意力、VAE 切片与分块。
  • 批量生成:支持多提示词与每提示词多图。

使用方式

安装命令:

pip install diffusers transformers accelerate torch
pip install xformers  # Optional: memory-efficient attention

基础文生图示例:

from diffusers import DiffusionPipeline
import torch

pipe = DiffusionPipeline.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-v1-5",
    torch_dtype=torch.float16
)
pipe.to("cuda")

image = pipe(
    "A serene mountain landscape at sunset, highly detailed",
    num_inference_steps=50,
    guidance_scale=7.5
).images[0]

image.save("output.png")

SDXL 示例:

from diffusers import AutoPipelineForText2Image
import torch

pipe = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    torch_dtype=torch.float16,
    variant="fp16"
)
pipe.to("cuda")
pipe.enable_model_cpu_offload()

image = pipe(
    prompt="A futuristic city with flying cars, cinematic lighting",
    height=1024,
    width=1024,
    num_inference_steps=30
).images[0]

图生图示例:

from diffusers import AutoPipelineForImage2Image
from PIL import Image

pipe = AutoPipelineForImage2Image.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-v1-5",
    torch_dtype=torch.float16
).to("cuda")

init_image = Image.open("input.jpg").resize((512, 512))

image = pipe(
    prompt="A watercolor painting of the scene",
    image=init_image,
    strength=0.75,
    num_inference_steps=50
).images[0]

图像修复示例:

from diffusers import AutoPipelineForInpainting
from PIL import Image

pipe = AutoPipelineForInpainting.from_pretrained(
    "runwayml/stable-diffusion-inpainting",
    torch_dtype=torch.float16
).to("cuda")

image = Image.open("photo.jpg")
mask = Image.open("mask.png")

result = pipe(
    prompt="A red car parked on the street",
    image=image,
    mask_image=mask,
    num_inference_steps=50
).images[0]

LoRA 加载示例:

from diffusers import DiffusionPipeline

pipe = DiffusionPipeline.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-v1-5",
    torch_dtype=torch.float16
).to("cuda")

pipe.load_lora_weights("path/to/lora", weight_name="style.safetensors")
image = pipe("A portrait in the trained style").images[0]
pipe.fuse_lora(lora_scale=0.8)
pipe.unload_lora_weights()

多个 LoRA:

pipe.load_lora_weights("lora1", adapter_name="style")
pipe.load_lora_weights("lora2", adapter_name="character")
pipe.set_adapters(["style", "character"], adapter_weights=[0.7, 0.5])
image = pipe("A portrait").images[0]

显存优化:

pipe.enable_model_cpu_offload()
pipe.enable_sequential_cpu_offload()
pipe.enable_attention_slicing()
pipe.enable_attention_slicing("max")
pipe.enable_xformers_memory_efficient_attention()
pipe.enable_vae_slicing()
pipe.enable_vae_tiling()

调度器切换:

from diffusers import DPMSolverMultistepScheduler

pipe.scheduler = DPMSolverMultistepScheduler.from_config(
    pipe.scheduler.config
)
image = pipe(prompt, num_inference_steps=20).images[0]

批量生成:

prompts = [
    "A cat playing piano",
    "A dog reading a book",
    "A bird painting a picture"
]
images = pipe(prompts, num_inference_steps=30).images

images = pipe(
    "A beautiful sunset",
    num_images_per_prompt=4,
    num_inference_steps=30
).images

适用场景

  • 需要从文本描述生成图像。
  • 进行图像到图像的转换(风格迁移、增强)。
  • 图像修复(填充遮罩区域)。
  • 图像外扩(扩展图像边界)。
  • 创建已有图像的变体。
  • 构建自定义图像生成工作流。

限制与替代方案

文档建议在以下情况使用替代方案:

  • DALL-E 3:用于无需 GPU 的基于 API 的生成。
  • Midjourney:用于艺术化、风格化输出。
  • Imagen:用于 Google Cloud 集成。
  • Leonardo.ai:用于基于 Web 的创意工作流。

常见问题

  • CUDA 显存不足:启用显存优化或使用更低精度。
  • 黑图/噪声图:检查 VAE 配置,必要时绕过安全检查器,确保 dtype 一致。
  • 生成缓慢:使用更快的调度器或减少步数。

智能体操作流程

  1. 检查环境:确认 GPU 显存、模型检查点与许可证、框架版本与输入格式。
  2. 确定输入:从数据或用户处确认格式、标识符与参数;对影响结果的任何值应询问而非猜测。
  3. 先运行小版本:先在低分辨率或短长度上对单个样本进行推理。
  4. 执行完整任务。
  5. 验证结果:定性检查输出并使用任务指标;检查生成内容的许可证限制。
  6. 报告:说明运行了什么(版本、命令、参数)、检查了什么、仍不确定什么。

完整性规则

  • 绝不捏造结果、参数、标识符、引用或统计数据。如果无法运行或验证,应明确说明。
  • 在商业或发布使用前检查模型与数据集许可证。
  • 将此处版本特定细节视为可能过时:对照已安装版本的官方文档进行确认。
  • 在涉及花钱、消耗共享 GPU 或云配额、触及个人或患者数据、或不可撤销的操作前先询问。

资源

  • 文档:https://huggingface.co/docs/diffusers
  • 仓库:https://github.com/huggingface/diffusers
  • 模型中心:https://huggingface.co/models?library=diffusers
  • Discord:https://discord.gg/diffusers