📖 定义
Diffusion Model(扩散模型)是一种生成式深度学习模型,通过模拟物理扩散过程来生成数据。它是DALL-E、Midjourney、Stable Diffusion等AI图像生成工具的核心技术。
核心思想:先给图像添加噪声(扩散过程),再学习逆向去噪(反向扩散),从而实现从随机噪声生成图像。
⚙️ 工作原理
前向扩散(Forward Diffusion)
逐步向图像添加高斯噪声,直到图像变成纯随机噪声。
反向扩散(Reverse Diffusion)
训练神经网络逐步去除噪声,从噪声中恢复出原始图像。
条件生成(Conditional Generation)
通过CLIP等编码器将文本描述转换为条件信号,指导生成特定内容的图像。
💡 应用场景
- AI绘画:DALL-E 3, Midjourney, Stable Diffusion
- 图像编辑:Inpainting, Outpainting
- 视频生成:Sora, Runway Gen
- 3D生成:Point-E, Shap-E
- 音频生成:Audio Diffusion
💻 代码示例
# 使用Hugging Face Diffusers生成图像
from diffusers import StableDiffusionPipeline
import torch
# 加载模型
pipe = StableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
torch_dtype=torch.float16
)
pipe = pipe.to("cuda")
# 生成图像
prompt = "a cute cat sitting on a cloud, sunset, digital art"
image = pipe(prompt, num_inference_steps=50).images[0]
# 保存图像
image.save("generated_cat.png")
# 使用ControlNet进行可控生成
from diffusers import ControlNetModel, StableDiffusionControlNetPipeline
controlnet = ControlNetModel.from_pretrained(
"lllyasviel/sd-controlnet-canny",
torch_dtype=torch.float16
)
pipe = StableDiffusionControlNetPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
controlnet=controlnet,
torch_dtype=torch.float16
).to("cuda")
# 用边缘图控制生成
image = pipe(prompt, control_image=canny_image).images[0]