10行代码搞定Stable Diffusion图像生成:AIGC小白实战笔记

关键词:Stable Diffusion、Diffusers、AIGC、10行代码、GPU、CPU


00 先上结果

把下面 10 行代码粘进 Colab / Jupyter / VS Code,回车即出图(示例耗时 8.3 秒,RTX 3060 12 GB):

from diffusers import StableDiffusionPipeline
import torch

pipe = StableDiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    torch_dtype=torch.float16,
    variant="fp16"
).to("cuda")

prompt = "a cat wearing steampunk goggles, cyberpunk city, 8k, ultra-realistic"
image = pipe(prompt, num_inference_steps=20, guidance_scale=7.5).images[0]
image.save("cat.png")

输出:

https://i.imgur.com/SteampunkCat.png (示例图,仅示意)


01 环境 3 步搞定

场景命令
Colab直接选 GPU 运行时,无需额外安装
本地pip install diffusers==0.30.0 transformers accelerate safetensors
CPU把 .to("cuda") 换成 .to("cpu"),速度约慢 20×,但能跑

02 10 行代码逐行拆解

 

作用小白翻译
1-2导入库工具箱
4-7下载并加载模型把「画家大脑」搬到本地
9写提示词告诉画家画啥
10生成真正开始画画
11保存把画存成 PNG

03 3 个超参数 30 秒上手

参数取值示例解释
num_inference_steps20–50步数越多细节越好,时间线性增加
guidance_scale7.5–12越大越「听话」,但过高会失真
negative_prompt"blurry, lowres"负面提示词,告诉画家 不要 画什么

04 CPU 党福利:一行代码提速 4×

pipe.enable_model_cpu_offload()   # 显存不足也能跑大图

05 Mac / AMD 也能跑

pipe = pipe.to("mps")  # Apple Silicon 专用

06 4 个常见报错 & 秒解方案

报错信息原因解决
CUDA out of memory显存不够加 pipe.enable_attention_slicing()
ImportError: libGL.so.1Linux 缺库apt-get install libgl1-mesa-glx
PIL.UnidentifiedImageError下载中断手动删缓存 ~/.cache/huggingface
RuntimeError: Expected mpsmacOS 版本低升级 macOS ≥ 12.3

07 30 秒变体:不同风格一句话切换

prompt = "portrait of an astronaut, art by greg rutkowski, soft lighting, trending on artstation"

→ 直接出油画质感

prompt = "pixel art cat, 16-bit, game sprite, black background"

→ 直接出像素风


08 进阶:30 行以内做「图生图」

from diffusers import StableDiffusionImg2ImgPipeline
from PIL import Image

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

init_img = Image.open("sketch.png").convert("RGB").resize((512, 512))
image = pipe(prompt="a detailed color version", image=init_img, strength=0.75).images[0]
image.save("colorized.png")

09 一键打包 Gradio 网页 Demo

import gradio as gr

def gen(prompt):
    return pipe(prompt).images[0]

gr.Interface(fn=gen, inputs="text", outputs="image").launch()


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值