使用Python在本地完整部署Stable Diffusion的操作指南
想要 AI 繪圖卻擔心隱私泄露?不想付費調(diào)用 API?本文帶你用 Python 在本地完整部署 Stable Diffusion,從環(huán)境搭建到出圖,手把手搞定屬于自己的 AI 畫師。
一、Stable Diffusion 是什么?
Stable Diffusion(SD)是一個開源的文本生成圖像(Text-to-Image)深度學習模型。只需輸入文字描述,就能生成高質(zhì)量的圖片。
1.1 為什么選擇本地部署?
┌────────────────────────────────────────────────────────┐ │ 云服務 vs 本地部署 對比 │ ├──────────────┬─────────────────┬───────────────────────┤ │ 維度 │ 云服務(Midjourney等) │ 本地部署(SD) │ ├──────────────┼─────────────────┼───────────────────────┤ │ 費用 │ 按月訂閱/按次計費 │ 一次性硬件投入 │ │ 隱私 │ 數(shù)據(jù)上傳云端 │ ? 完全本地,無泄露風險 │ │ 自由度 │ 受平臺審核限制 │ ? 無限制 │ │ 可定制性 │ 固定模型 │ ? 任意切換模型/LoRA │ │ API 集成 │ 受限/需付費 │ ? Python 完全控制 │ │ 硬件要求 │ 無 │ 需要 NVIDIA GPU │ └──────────────┴─────────────────┴───────────────────────┘
1.2 SD 版本演進
SD 1.4 (2022) → SD 1.5 (2022) → SD 2.0/2.1 (2022) → SDXL (2023) → SD 3.0 (2024) → SD 3.5 (2024) │ │ │ └── 經(jīng)典穩(wěn)定 ─────┘ └── 高質(zhì)量,推薦使用
二、硬件與環(huán)境要求
2.1 最低 / 推薦配置
| 硬件 | 最低要求 | 推薦配置 |
|---|---|---|
| GPU | NVIDIA 8GB VRAM | NVIDIA 12GB+ VRAM (RTX 3060+) |
| 內(nèi)存 | 16 GB | 32 GB |
| 硬盤 | 10 GB | 50 GB+ SSD |
| CUDA | 11.7+ | 12.x |
2.2 環(huán)境搭建
# 1. 創(chuàng)建 Python 虛擬環(huán)境(推薦 Python 3.10)
conda create -n sd python=3.10 -y
conda activate sd
# 2. 安裝 PyTorch(CUDA 12.1 版本)
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
# 3. 驗證 CUDA 是否可用
python -c "import torch; print(f'CUDA: {torch.cuda.is_available()}, GPU: {torch.cuda.get_device_name(0)}')"
# 輸出示例: CUDA: True, GPU: NVIDIA GeForce RTX 4060三、方案一:Diffusers 庫 —— 適合開發(fā)者
diffusers 是 HuggingFace 官方的擴散模型庫,純 Python API 調(diào)用,最適合 Python 開發(fā)者集成到自己的項目中。
3.1 安裝
pip install diffusers transformers accelerate safetensors
3.2 基礎文生圖(Text-to-Image)
import torch
from diffusers import StableDiffusionPipeline
def basic_text2img(prompt: str, output_path: str = "output.png"):
"""
基礎文生圖 —— 輸入文字,輸出圖片
流程: 文字描述 → CLIP 編碼 → UNet 去噪 → VAE 解碼 → 圖片
"""
# 加載模型(首次會自動下載,約 4~7 GB)
pipe = StableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
torch_dtype=torch.float16, # 半精度,節(jié)省顯存
safety_checker=None # 關閉安全檢查(可選)
)
pipe.to("cuda")
# 開啟顯存優(yōu)化
pipe.enable_attention_slicing() # 分塊注意力,減少顯存占用
# 生成圖片
image = pipe(
prompt=prompt,
num_inference_steps=30, # 去噪步數(shù)(20~50,越多越精細)
guidance_scale=7.5, # CFG 引導系數(shù)(7~12,越大越貼合描述)
width=512,
height=512
).images[0]
image.save(output_path)
print(f"圖片已保存: {output_path}")
return image
# 使用示例
basic_text2img(
"a beautiful sunset over the ocean, highly detailed, 4k, photorealistic",
"sunset.png"
)3.3 使用 SDXL 模型(更高質(zhì)量)
from diffusers import StableDiffusionXLPipeline
def sdxl_text2img(prompt: str, output_path: str = "sdxl_output.png"):
"""
SDXL 文生圖 —— 質(zhì)量遠超 SD 1.5
SDXL 優(yōu)勢:
- 默認 1024x1024 分辨率
- 更好的文字理解能力
- 更真實的色彩和細節(jié)
"""
pipe = StableDiffusionXLPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
torch_dtype=torch.float16,
variant="fp16"
)
pipe.to("cuda")
# 顯存優(yōu)化(SDXL 模型更大,優(yōu)化更必要)
pipe.enable_attention_slicing()
pipe.enable_vae_slicing()
image = pipe(
prompt=prompt,
negative_prompt="blurry, low quality, distorted, deformed",
num_inference_steps=40,
guidance_scale=8.0,
width=1024,
height=1024
).images[0]
image.save(output_path)
print(f"SDXL 圖片已保存: {output_path}")
return image3.4 關鍵參數(shù)詳解
┌─────────────────────────────────────────────────────────────┐ │ Stable Diffusion 核心參數(shù) │ ├─────────────────┬───────────────────────────────────────────┤ │ 參數(shù) │ 說明 │ ├─────────────────┼───────────────────────────────────────────┤ │ prompt │ 正向提示詞:描述你想要的畫面 │ │ negative_prompt │ 反向提示詞:描述你不想要的元素 │ │ num_inference_steps │ 去噪步數(shù):20~50(↑ 質(zhì)量 ↑ 速度 ↓) │ │ guidance_scale │ CFG 值:7~12(↑ 越貼合文字 ↑ 畫面可能僵硬) │ │ width / height │ 圖片尺寸:512/768/1024 │ │ seed │ 隨機種子:固定種子可復現(xiàn)同一張圖 │ └─────────────────┴───────────────────────────────────────────┘
3.5 顯存不足的解決方案
def low_vram_generate(pipe, prompt, output_path="output.png"):
"""
低顯存生成方案(4~6 GB VRAM 也能跑)
"""
# 1. CPU 卸載:模型按需加載到 GPU,用完即卸回 CPU
pipe.enable_model_cpu_offload()
# 2. 分塊注意力:降低注意力計算的峰值顯存
pipe.enable_attention_slicing()
# 3. VAE 分塊:VAE 解碼時分塊處理
pipe.enable_vae_slicing()
# 4. 降低分辨率
image = pipe(
prompt=prompt,
width=512,
height=512,
num_inference_steps=20 # 減少步數(shù)
).images[0]
image.save(output_path)四、方案二:Stable Diffusion WebUI —— 適合非開發(fā)者
如果你更偏好圖形界面操作,AUTOMATIC1111 的 WebUI 是最受歡迎的選擇。
4.1 安裝 WebUI
# 1. 克隆倉庫 git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git cd stable-diffusion-webui # 2. Windows 用戶直接運行 ./webui.bat # 3. Linux 用戶 ./webui.sh
啟動后瀏覽器自動打開 http://127.0.0.1:7860,即可看到 Web 界面。
4.2 通過 Python 調(diào)用 WebUI API
import requests
import base64
from pathlib import Path
def sd_webui_api(prompt: str, output_path: str = "api_output.png"):
"""
通過 API 調(diào)用本地 WebUI
先啟動 WebUI: ./webui.bat --api
"""
url = "http://127.0.0.1:7860/sdapi/v1/txt2img"
payload = {
"prompt": prompt,
"negative_prompt": "blurry, low quality, deformed",
"steps": 30,
"cfg_scale": 7.5,
"width": 512,
"height": 512,
"sampler_name": "DPM++ 2M Karras",
"seed": -1 # -1 表示隨機
}
response = requests.post(url, json=payload)
result = response.json()
# 解碼并保存圖片
image_data = base64.b64decode(result["images"][0])
with open(output_path, "wb") as f:
f.write(image_data)
print(f"API 生成完成: {output_path}")
# 返回種子值,方便復現(xiàn)
info = result.get("info", {})
print(f"Seed: {info.get('seed', 'unknown')}")
# 使用
sd_webui_api("a cyberpunk city at night, neon lights, rain, 4k")五、模型管理
5.1 下載模型
"""
模型下載指南
推薦模型來源:
1. HuggingFace: https://huggingface.co/models?pipeline_tag=text-to-image
2. Civitai: https://civitai.com (最大的 SD 模型社區(qū))
常用模型:
"""
MODELS = {
# ---- SD 1.5 系列 ----
"sd15": "runwayml/stable-diffusion-v1-5",
"anything-v5": "stablediffusionapi/anything-v5", # 二次元風格
"realistic-vision": "SG161222/Realistic_Vision_V5.1", # 真實人像
# ---- SDXL 系列 ----
"sdxl": "stabilityai/stable-diffusion-xl-base-1.0",
"sdxl-turbo": "stabilityai/sdxl-turbo", # 快速生成
"juggernaut-xl": "RunDiffusion/Juggernaut-XL-v9", # 綜合高質(zhì)量
# ---- SD 3.0+ ----
"sd3": "stabilityai/stable-diffusion-3-medium",
}5.2 加載本地模型
from diffusers import StableDiffusionPipeline
def load_local_model(model_path: str):
"""
加載本地模型文件(.safetensors 或 HuggingFace 格式)
model_path 可以是:
- 本地文件夾路徑: "./models/sd15"
- HuggingFace repo: "runwayml/stable-diffusion-v1-5"
- 本地 .safetensors 文件: "./models/model.safetensors"
"""
pipe = StableDiffusionPipeline.from_single_file(
model_path,
torch_dtype=torch.float16
)
pipe.to("cuda")
return pipe
5.3 LoRA 微調(diào)風格
def apply_lora(pipe, lora_path: str, lora_scale: float = 0.8):
"""
加載 LoRA 風格微調(diào)
LoRA: 輕量級適配器,可以在不修改基礎模型的情況下改變畫風
例如: 動漫風、水彩風、某位畫師風格等
"""
pipe.load_lora_weights(lora_path)
# 生成時通過 cross_attention_kwargs 控制強度
image = pipe(
prompt="a girl in a garden, masterpiece",
cross_attention_kwargs={"scale": lora_scale}
).images[0]
return image
六、高級功能
6.1 圖生圖(Image-to-Image)
from diffusers import StableDiffusionImg2ImgPipeline
from PIL import Image
def image_to_image(init_image_path: str, prompt: str, strength: float = 0.7):
"""
圖生圖:在已有圖片基礎上進行 AI 重繪
參數(shù):
init_image_path: 原始圖片路徑
prompt: 重繪提示詞
strength: 重繪強度 (0.0~1.0)
0.3 → 輕微修改
0.7 → 中等改變
0.9 → 幾乎完全重繪
"""
init_image = Image.open(init_image_path).convert("RGB")
init_image = init_image.resize((512, 512))
pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
torch_dtype=torch.float16
).to("cuda")
image = pipe(
prompt=prompt,
image=init_image,
strength=strength,
num_inference_steps=30
).images[0]
image.save("img2img_output.png")
print("圖生圖完成")
return image
# 示例: 將照片轉為油畫風格
image_to_image("photo.jpg", "oil painting style, masterpiece, highly detailed")
6.2 圖片局部重繪(Inpainting)
from diffusers import StableDiffusionInpaintPipeline
def inpaint(image_path, mask_path, prompt):
"""
局部重繪:只修改圖片中被遮罩覆蓋的區(qū)域
應用場景:
- 移除圖片中的某個物體
- 替換背景
- 修改人物服裝
"""
image = Image.open(image_path).resize((512, 512))
mask = Image.open(mask_path).convert("L").resize((512, 512))
pipe = StableDiffusionInpaintPipeline.from_pretrained(
"runwayml/stable-diffusion-inpainting",
torch_dtype=torch.float16
).to("cuda")
result = pipe(
prompt=prompt,
image=image,
mask_image=mask,
num_inference_steps=30
).images[0]
result.save("inpaint_output.png")
6.3 ControlNet —— 精準控制構圖
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
from diffusers.utils import load_image
def controlnet_canny(image_path: str, prompt: str):
"""
ControlNet: 通過邊緣檢測圖控制 AI 生成的構圖
支持多種控制模式:
- Canny 邊緣: 精確輪廓控制
- Depth 深度: 空間結構控制
- Pose 姿態(tài): 人體姿態(tài)控制
- Scribble: 涂鴉草圖控制
"""
# 加載 ControlNet 模型
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")
# 加載輸入圖片并提取邊緣
input_image = load_image(image_path)
import cv2
import numpy as np
image_np = np.array(input_image)
canny_image = cv2.Canny(image_np, 100, 200)
canny_image = Image.fromarray(canny_image)
# 生成
image = pipe(
prompt=prompt,
image=canny_image,
num_inference_steps=30,
guidance_scale=7.5
).images[0]
image.save("controlnet_output.png")
七、批量生成與自動化
7.1 批量生成不同風格
def batch_generate(pipe, base_prompt: str, styles: list, output_dir: str = "./outputs"):
"""
批量生成不同風格的圖片
"""
import os
os.makedirs(output_dir, exist_ok=True)
for i, style in enumerate(styles):
prompt = f"{base_prompt}, {style}"
image = pipe(
prompt=prompt,
num_inference_steps=30,
guidance_scale=7.5
).images[0]
filename = f"{output_dir}/gen_{i:03d}_{style.replace(' ', '_')}.png"
image.save(filename)
print(f"[{i+1}/{len(styles)}] 已生成: {filename}")
# 使用
pipe = StableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
torch_dtype=torch.float16
).to("cuda")
batch_generate(
pipe,
base_prompt="a beautiful mountain landscape",
styles=[
"oil painting style",
"watercolor painting",
"anime style",
"photorealistic, 8k",
"cyberpunk neon",
"studio ghibli style"
]
)
7.2 固定種子復現(xiàn)結果
def reproducible_generation(pipe, prompt: str, seed: int = 42):
"""
固定隨機種子,確保每次生成完全相同的圖片
適用于: 測試、對比不同提示詞效果、分享參數(shù)
"""
import torch
generator = torch.Generator("cuda").manual_seed(seed)
image = pipe(
prompt=prompt,
generator=generator,
num_inference_steps=30
).images[0]
image.save(f"seed_{seed}.png")
return image
八、Prompt 提示詞工程
8.1 提示詞結構模板
┌─────────────────────────────────────────────────────────────┐ │ 提示詞萬能公式 │ │ │ │ [主體] + [場景/環(huán)境] + [光線] + [風格] + [畫質(zhì)詞] │ │ │ │ 示例: │ │ a young woman (主體) │ │ standing in a cherry blossom garden (場景) │ │ golden hour lighting, soft shadows (光線) │ │ oil painting style (風格) │ │ masterpiece, best quality, highly detailed, 4k (畫質(zhì)詞) │ └─────────────────────────────────────────────────────────────┘
8.2 常用畫質(zhì)增強詞
QUALITY_BOOSTERS = [
# 通用畫質(zhì)
"masterpiece", "best quality", "highly detailed",
"sharp focus", "8k uhd", "high resolution",
# 光影
"cinematic lighting", "volumetric lighting",
"golden hour", "dramatic lighting",
# 攝影效果
"bokeh", "depth of field", "film grain",
"DSLR, 35mm lens", "RAW photo",
]
NEGATIVE_PROMPT = (
"blurry, low quality, low resolution, "
"deformed, distorted, disfigured, bad anatomy, "
"bad hands, missing fingers, extra fingers, "
"watermark, text, logo, signature"
)
九、完整工具類封裝
"""
SDToolKit —— 一個封裝好的 Stable Diffusion 工具類
"""
import torch
from PIL import Image
from pathlib import Path
from diffusers import StableDiffusionPipeline
class SDToolKit:
"""Stable Diffusion 本地生成工具包"""
def __init__(self, model_name: str = "runwayml/stable-diffusion-v1-5"):
print(f"正在加載模型: {model_name} ...")
self.pipe = StableDiffusionPipeline.from_pretrained(
model_name,
torch_dtype=torch.float16,
safety_checker=None
)
self.pipe.to("cuda")
self.pipe.enable_attention_slicing()
print("模型加載完成!")
def generate(
self,
prompt: str,
negative_prompt: str = "",
width: int = 512,
height: int = 512,
steps: int = 30,
cfg_scale: float = 7.5,
seed: int = -1,
output_path: str = None
) -> Image.Image:
"""生成圖片"""
generator = None
if seed != -1:
generator = torch.Generator("cuda").manual_seed(seed)
result = self.pipe(
prompt=prompt,
negative_prompt=negative_prompt,
width=width,
height=height,
num_inference_steps=steps,
guidance_scale=cfg_scale,
generator=generator
)
image = result.images[0]
if output_path:
Path(output_path).parent.mkdir(parents=True, exist_ok=True)
image.save(output_path)
print(f"已保存: {output_path}")
return image
def batch_generate(self, prompts: list, output_dir: str = "./outputs"):
"""批量生成"""
Path(output_dir).mkdir(exist_ok=True)
images = []
for i, prompt in enumerate(prompts):
path = f"{output_dir}/img_{i:03d}.png"
img = self.generate(prompt=prompt, output_path=path)
images.append(img)
print(f"\n批量生成完成!共 {len(images)} 張圖片")
return images
# ===== 使用示例 =====
if __name__ == "__main__":
sd = SDToolKit("runwayml/stable-diffusion-v1-5")
# 單張生成
sd.generate(
prompt="a cute cat wearing a tiny hat, masterpiece, best quality",
negative_prompt="blurry, deformed, bad anatomy",
output_path="outputs/cat.png"
)
# 批量生成
sd.batch_generate([
"a serene lake at sunrise, photorealistic, 8k",
"a cyberpunk street, neon lights, rain, highly detailed",
"a medieval castle on a cliff, fantasy art, epic",
"a steaming cup of coffee on a wooden table, cozy atmosphere"
])
十、常見問題排查
┌──────────────────────────────────────────────────────────────┐ │ 常見問題 & 解決方案 │ ├─────────────────────────────┬────────────────────────────────┤ │ 問題 │ 解決方案 │ ├─────────────────────────────┼────────────────────────────────┤ │ CUDA out of memory │ 減小分辨率/降低 steps/開啟 │ │ │ attention_slicing │ ├─────────────────────────────┼────────────────────────────────┤ │ 生成的圖片全黑 │ 檢查 safety_checker 是否誤判; │ │ │ 調(diào)整 prompt 避開敏感詞 │ ├─────────────────────────────┼────────────────────────────────┤ │ 圖片模糊/質(zhì)量差 │ 提高 steps(30+); 添加畫質(zhì)詞; │ │ │ 嘗試更好的模型(SDXL) │ ├─────────────────────────────┼────────────────────────────────┤ │ 手指/人臉畸形 │ 使用負面提示詞; 嘗試 SDXL; │ │ │ 后期用 inpaint 修復 │ ├─────────────────────────────┼────────────────────────────────┤ │ 下載模型太慢 │ 使用鏡像站; 手動下載 .safeten- │ │ │ sors 文件到本地 │ ├─────────────────────────────┼────────────────────────────────┤ │ 生成速度太慢 │ 使用 sdxl-turbo; 降低 steps; │ │ │ 開啟 xformers; 升級 GPU │ └─────────────────────────────┴────────────────────────────────┘
十一、學習路線
入門 ────────────────────────────────────────────── 進階 SD 1.5 文生圖 │ ├── 掌握提示詞工程 ├── 學會參數(shù)調(diào)優(yōu) │ ▼ SDXL 高質(zhì)量生成 │ ├── 圖生圖 (img2img) ├── 局部重繪 (inpainting) │ ▼ ControlNet 精準控制 │ ├── Canny / Depth / Pose ├── LoRA 風格微調(diào) │ ▼ 進階玩法 │ ├── ComfyUI 工作流 ├── 訓練自定義 LoRA ├── 視頻生成 (SVD) └── 集成到 Web 應用
總結
本文完整覆蓋了 Stable Diffusion 本地部署的核心內(nèi)容:
- Diffusers 純 Python API 方案 —— 適合開發(fā)者集成
- WebUI 圖形界面方案 —— 適合快速上手和 API 調(diào)用
- 高級功能:圖生圖、局部重繪、ControlNet
- 批量生成、顯存優(yōu)化、提示詞工程
以上就是使用Python在本地完整部署Stable Diffusion的操作指南的詳細內(nèi)容,更多關于Python本地部署Stable Diffusion的資料請關注腳本之家其它相關文章!
相關文章
python安裝cxOracle避坑總結不要直接pip install
這篇文章主要為大家介紹了python安裝cx_Oracle是遇到的一些問題的解決辦法的總結,來幫大家避避坑有需要的朋友可以借鑒參考下,希望能夠有所幫助祝大家多多進步2021-10-10
Python數(shù)據(jù)處理篇之Sympy系列(五)---解方程
這篇文章主要介紹了Python數(shù)據(jù)處理篇之Sympy系列(五)---解方程,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-10-10
Python操作PostgreSql數(shù)據(jù)庫的方法(基本的增刪改查)
這篇文章主要介紹了Python操作PostgreSql數(shù)據(jù)庫(基本的增刪改查),本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12
基于Python編寫MySQL數(shù)據(jù)庫備份腳本
這篇文章主要為大家詳細介紹了一個使用Python編寫的MySQL數(shù)據(jù)庫備份腳本,包含壓縮,日志記錄和自動清理舊備份功能,有需要的可以參考一下2025-06-06

