mcpField
S
stable-diffusion-image-generation

stable-diffusion-image-generation

github.com/davila7クリエイティブ・メディア33.0k1.7k 回インストール今日更新
リポジトリ

stable-diffusion-image-generation について

stable-diffusion-image-generationは、HuggingFace Diffusersによる画像生成のガイドです。画像ワークフローを構築する開発者向けに、テキスト・画像入力、空間条件付け、アダプター、メモリ調整を扱います。

主な機能

  1. 01テキストから画像・画像から画像への生成
  2. 02インペインティングとアウトペインティング
  3. 03ControlNetによる空間条件付け
  4. 04LoRAアダプター対応
  5. 05スケジューラー選択とメモリ最適化

活用シーン

  1. 01テキストプロンプトから画像を生成
  2. 02テキストの指示で画像を変換
  3. 03マスク領域の補完や画像境界の拡張
  4. 04エッジ、ポーズ、深度を条件にした生成

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/davila7/claude-code-templates --skill stable-diffusion-image-generation

インストール後、Claude Code で/stable-diffusion-image-generationを入力して読み込まれたか確認します。

同梱ファイルreferences/advanced-usage.mdreferences/troubleshooting.md

詳細

Stable Diffusion 画像生成

HuggingFace Diffusers ライブラリを使用して Stable Diffusion で画像を生成するための包括的なガイドです。

Stable Diffusion を使用する場合

次の場合に Stable Diffusion を使用してください:

  • テキストによる説明から画像を生成する場合
  • 画像から画像への変換(スタイル転送、画質向上)を行う場合
  • インペインティング(マスクされた領域の補完)を行う場合
  • アウトペインティング(画像の境界を超えた拡張)を行う場合
  • 既存の画像のバリエーションを作成する場合
  • カスタムの画像生成ワークフローを構築する場合

主な機能:

  • テキストから画像: 自然言語のプロンプトから画像を生成します
  • 画像から画像: テキストによるガイダンスで既存の画像を変換します
  • インペインティング: 文脈を考慮したコンテンツでマスクされた領域を埋めます
  • ControlNet: 空間的な条件付け(エッジ、ポーズ、深度)を追加します
  • LoRA サポート: 効率的なファインチューニングとスタイルの適応を行います
  • 複数のモデル: SD 1.5、SDXL、SD 3.0、Flux に対応しています

代わりに使用できるもの:

  • DALL-E 3: GPU を使用しない API ベースの生成向け
  • Midjourney: 芸術的でスタイライズされた出力向け
  • Imagen: Google Cloud との統合向け
  • Leonardo.ai: Web ベースのクリエイティブワークフロー向け

クイックスタート

インストール
pip install diffusers transformers accelerate torch
pip install xformers  # Optional: memory-efficient attention
基本的なテキストから画像への生成
from diffusers import DiffusionPipeline
import torch

# Load pipeline (auto-detects model type)
pipe = DiffusionPipeline.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-v1-5",
    torch_dtype=torch.float16
)
pipe.to("cuda")

# Generate image
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")

# Enable memory optimization
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]

アーキテクチャの概要

3 つの柱による設計

Diffusers は 3 つの中核コンポーネントを中心に構築されています:

Pipeline (orchestration)
├── Model (neural networks)
│   ├── UNet / Transformer (noise prediction)
│   ├── VAE (latent encoding/decoding)
│   └── Text Encoder (CLIP/T5)
└── Scheduler (denoising algorithm)
パイプラインの推論フロー
Text Prompt → Text Encoder → Text Embeddings
                                    ↓
Random Noise → [Denoising Loop] ← Scheduler
                      ↓
               Predicted Noise
                      ↓
              VAE Decoder → Final Image

基本概念

パイプライン

パイプラインは完全なワークフローを統括します:

パイプライン用途
StableDiffusionPipelineテキストから画像(SD 1.x/2.x)
StableDiffusionXLPipelineテキストから画像(SDXL)
StableDiffusion3Pipelineテキストから画像(SD 3.0)
FluxPipelineテキストから画像(Flux モデル)
StableDiffusionImg2ImgPipeline画像から画像
StableDiffusionInpaintPipelineインペインティング
スケジューラー

スケジューラーはノイズ除去プロセスを制御します:

スケジューラーステップ数品質ユースケース
EulerDiscreteScheduler20-50良好標準的な選択
EulerAncestralDiscreteScheduler20-50良好より多様な出力
DPMSolverMultistepScheduler15-25優秀高速かつ高品質
DDIMScheduler50-100良好決定論的
LCMScheduler4-8良好非常に高速
UniPCMultistepScheduler15-25優秀高速な収束
スケジューラーの入れ替え
from diffusers import DPMSolverMultistepScheduler

# Swap for faster generation
pipe.scheduler = DPMSolverMultistepScheduler.from_config(
    pipe.scheduler.config
)

# Now generate with fewer steps
image = pipe(prompt, num_inference_steps=20).images[0]

生成パラメータ

主要なパラメータ
パラメータデフォルト説明
prompt必須目的の画像のテキストによる説明
negative_promptなし画像に含めたくない要素
num_inference_steps50ノイズ除去のステップ数(多いほど高品質)
guidance_scale7.5プロンプトへの忠実度(通常 7〜12)
height, width512/1024出力サイズ(8 の倍数)
generatorなし再現性のための Torch ジェネレーター
num_images_per_prompt1バッチサイズ
再現可能な生成
import torch

generator = torch.Generator(device="cuda").manual_seed(42)

image = pipe(
    prompt="A cat wearing a top hat",
    generator=generator,
    num_inference_steps=50
).images[0]
ネガティブプロンプト
image = pipe(
    prompt="Professional photo of a dog in a garden",
    negative_prompt="blurry, low quality, distorted, ugly, bad anatomy",
    guidance_scale=7.5
).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,  # How much to transform (0-1)
    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")  # White = inpaint region

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

ControlNet

正確な制御のために空間的な条件付けを追加します:

from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
import torch

# Load ControlNet for edge conditioning
controlnet = ControlNetModel.from_pretrained(
    "lllyasviel/control_v11p_sd15_canny",
    torch_dtype=torch.float16
)

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

# Use Canny edge image as control
control_image = get_canny_image(input_image)

image = pipe(
    prompt="A beautiful house in the style of Van Gogh",
    image=control_image,
    num_inference_steps=30
).images[0]
利用可能な ControlNet
ControlNet入力タイプユースケース
cannyエッジマップ構造の維持
openposeポーズスケルトン人物のポーズ
depth深度マップ3D を意識した生成
normal法線マップ表面のディテール
mlsd線分建築的な線
scribble大まかなスケッチスケッチから画像

LoRA アダプター

ファインチューニング済みのスタイルアダプターを読み込みます:

from diffusers import DiffusionPipeline

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

# Load LoRA weights
pipe.load_lora_weights("path/to/lora", weight_name="style.safetensors")

# Generate with LoRA style
image = pipe("A portrait in the trained style").images[0]

# Adjust LoRA strength
pipe.fuse_lora(lora_scale=0.8)

# Unload LoRA
pipe.unload_lora_weights()
複数の LoRA
# Load multiple LoRAs
pipe.load_lora_weights("lora1", adapter_name="style")
pipe.load_lora_weights("lora2", adapter_name="character")

# Set weights for each
pipe.set_adapters(["style", "character"], adapter_weights=[0.7, 0.5])

image = pipe("A portrait").images[0]

メモリの最適化

CPU オフロードの有効化
# Model CPU offload - moves models to CPU when not in use
pipe.enable_model_cpu_offload()

# Sequential CPU offload - more aggressive, slower
pipe.enable_sequential_cpu_offload()
アテンションスライシング
# Reduce memory by computing attention in chunks
pipe.enable_attention_slicing()

# Or specific chunk size
pipe.enable_attention_slicing("max")
xFormers によるメモリ効率の良いアテンション
# Requires xformers package
pipe.enable_xformers_memory_efficient_attention()
大きな画像向けの VAE スライシング
# Decode latents in tiles for large images
pipe.enable_vae_slicing()
pipe.enable_vae_tiling()

モデルのバリエーション

異なる精度での読み込み
# FP16 (recommended for GPU)
pipe = DiffusionPipeline.from_pretrained(
    "model-id",
    torch_dtype=torch.float16,
    variant="fp16"
)

# BF16 (better precision, requires Ampere+ GPU)
pipe = DiffusionPipeline.from_pretrained(
    "model-id",
    torch_dtype=torch.bfloat16
)
特定のコンポーネントの読み込み
from diffusers import UNet2DConditionModel, AutoencoderKL

# Load custom VAE
vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse")

# Use with pipeline
pipe = DiffusionPipeline.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-v1-5",
    vae=vae,
    torch_dtype=torch.float16
)

バッチ生成

複数の画像を効率的に生成します:

# Multiple prompts
prompts = [
    "A cat playing piano",
    "A dog reading a book",
    "A bird painting a picture"
]

images = pipe(prompts, num_inference_steps=30).images

# Multiple images per prompt
images = pipe(
    "A beautiful sunset",
    num_images_per_prompt=4,
    num_inference_steps=30
).images

よくあるワークフロー

ワークフロー 1: 高品質生成
from diffusers import StableDiffusionXLPipeline, DPMSolverMultistepScheduler
import torch

# 1. Load SDXL with optimizations
pipe = StableDiffusionXLPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    torch_dtype=torch.float16,
    variant="fp16"
)
pipe.to("cuda")
pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
pipe.enable_model_cpu_offload()

# 2. Generate with quality settings
image = pipe(
    prompt="A majestic lion in the savanna, golden hour lighting, 8k, detailed fur",
    negative_prompt="blurry, low quality, cartoon, anime, sketch",
    num_inference_steps=30,
    guidance_scale=7.5,
    height=1024,
    width=1024
).images[0]
ワークフロー 2: 高速プロトタイピング
from diffusers import AutoPipelineForText2Image, LCMScheduler
import torch

# Use LCM for 4-8 step generation
pipe = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    torch_dtype=torch.float16
).to("cuda")

# Load LCM LoRA for fast generation
pipe.load_lora_weights("latent-consistency/lcm-lora-sdxl")
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
pipe.fuse_lora()

# Generate in ~1 second
image = pipe(
    "A beautiful landscape",
    num_inference_steps=4,
    guidance_scale=1.0
).images[0]

よくある問題

CUDA out of memory:

# Enable memory optimizations
pipe.enable_model_cpu_offload()
pipe.enable_attention_slicing()
pipe.enable_vae_slicing()

# Or use lower precision
pipe = DiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)

黒い画像・ノイズの多い画像:

# Check VAE configuration
# Use safety checker bypass if needed
pipe.safety_checker = None

# Ensure proper dtype consistency
pipe = pipe.to(dtype=torch.float16)

生成が遅い:

# Use faster scheduler
from diffusers import DPMSolverMultistepScheduler
pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)

# Reduce steps
image = pipe(prompt, num_inference_steps=20).images[0]

リファレンス

リソース

コメント