stable-diffusion-image-generation について
stable-diffusion-image-generationは、HuggingFace Diffusersによる画像生成のガイドです。画像ワークフローを構築する開発者向けに、テキスト・画像入力、空間条件付け、アダプター、メモリ調整を扱います。
主な機能
- 01テキストから画像・画像から画像への生成
- 02インペインティングとアウトペインティング
- 03ControlNetによる空間条件付け
- 04LoRAアダプター対応
- 05スケジューラー選択とメモリ最適化
活用シーン
- 01テキストプロンプトから画像を生成
- 02テキストの指示で画像を変換
- 03マスク領域の補完や画像境界の拡張
- 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 | インペインティング |
スケジューラー
スケジューラーはノイズ除去プロセスを制御します:
| スケジューラー | ステップ数 | 品質 | ユースケース |
|---|---|---|---|
EulerDiscreteScheduler | 20-50 | 良好 | 標準的な選択 |
EulerAncestralDiscreteScheduler | 20-50 | 良好 | より多様な出力 |
DPMSolverMultistepScheduler | 15-25 | 優秀 | 高速かつ高品質 |
DDIMScheduler | 50-100 | 良好 | 決定論的 |
LCMScheduler | 4-8 | 良好 | 非常に高速 |
UniPCMultistepScheduler | 15-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_steps | 50 | ノイズ除去のステップ数(多いほど高品質) |
guidance_scale | 7.5 | プロンプトへの忠実度(通常 7〜12) |
height, width | 512/1024 | 出力サイズ(8 の倍数) |
generator | なし | 再現性のための Torch ジェネレーター |
num_images_per_prompt | 1 | バッチサイズ |
再現可能な生成
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]
リファレンス
- 高度な使い方 - カスタムパイプライン、ファインチューニング、デプロイ
- トラブルシューティング - よくある問題と解決策
リソース
- ドキュメント: https://huggingface.co/docs/diffusers
- リポジトリ: https://github.com/huggingface/diffusers
- Model Hub: https://huggingface.co/models?library=diffusers
- Discord: https://discord.gg/diffusers
コメント
Markdown 対応