
本文仅用于技术分享和学习交流,内容不包含任何广告、推广、引流、付费课程或外链信息,即便出现链接地址也均为相关产品的官网地址(来自于网络公开资料)所有示例和配置均为技术实践,仅供参考。
本文档记录了从零开始在本地部署 Stable Diffusion XL(SDXL)AI 绘画模型的完整过程,包括环境配置、依赖安装、模型下载、提示词编写技巧以及实战示例。
打开命令提示符(CMD),输入:
python --versionPython 3.11.9)→ 已安装,跳到「一、测试环境」关闭并重新打开命令提示符,输入:
python --version显示版本号即安装成功:
Python 3.11.9pip --version显示类似以下内容即正常:
pip 24.0 from D:\Program Files\Python311\Lib\site-packages\pip (python 3.11)原因: 安装时没有勾选「Add Python to PATH」
解决方案 1:重新安装
解决方案 2:手动添加环境变量
Path,点击编辑D:\Program Files\Python311\D:\Program Files\Python311\Scripts\说明: 以下是博主个人电脑的配置环境,本文档所有操作和测试结果均基于此环境。不同的硬件配置可能会有不同的表现,仅供参考。
项目 | 配置 |
|---|---|
操作系统 | Windows 10 |
Python 版本 | 3.11.9 |
显卡 | NVIDIA GeForce RTX 3060 (12GB 显存) |
CUDA 版本 | 12.4 |
PyTorch | 2.6.0+cu124 |
模型 | Stable Diffusion XL Base 1.0 |
官网写法:
pip install modelscope推荐写法(国内用户):
pip install modelscope -i https://mirrors.aliyun.com/pypi/simple/两者区别:
命令 | 下载来源 | 速度 |
|---|---|---|
| PyPI 官方源(国外服务器) | 国内较慢 |
| 国内镜像服务器 | 快很多 |
-i是--index-url的缩写,用于指定下载源。安装的包完全相同,只是下载速度不同。
重要:必须安装 CUDA 版本的 PyTorch,否则无法使用 GPU 加速!
# 安装 CUDA 12.4 版本的 PyTorch
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124说明: 如果之前安装过 CPU 版本的 PyTorch,直接运行上面命令会自动覆盖安装。如果担心冲突,可以先卸载:
pip uninstall torch torchvision torchaudio -y
如何检查? 运行以下命令验证:
python -c "import torch; print('PyTorch:', torch.__version__); print('CUDA可用:', torch.cuda.is_available())"正确的输出(CUDA 版本):
PyTorch: 2.6.0+cu124
CUDA可用: True注意版本号后面的
+cu124,说明安装的是 CUDA 12.4 版本
错误的输出(CPU 版本):
PyTorch: 2.9.1+cpu
CUDA可用: False注意版本号后面的
+cpu,说明安装的是 CPU 版本,无法使用 GPU
原因:
pip install torch 默认安装的是 CPU 版本解决方案:
第一步:卸载错误的 CPU 版本
pip uninstall torch torchvision torchaudio -y第二步:从 PyTorch 官方源安装 CUDA 版本
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124第三步:重新验证
python -c "import torch; print('PyTorch:', torch.__version__); print('CUDA可用:', torch.cuda.is_available())"确认输出 CUDA可用: True 即修复成功。
pip install "diffusers>=0.36.0" -i https://mirrors.aliyun.com/pypi/simple/核心库的作用:
库名 | 作用 |
|---|---|
torch | PyTorch 深度学习框架,模型运行的"引擎" |
diffusers | 扩散模型库,提供 SDXL 模型加载和推理 |
python --version
# 输出: Python 3.11.9nvidia-smi正常会显示显卡型号、驱动版本、显存使用情况等信息。
如果提示「不是内部或外部命令」,说明 NVIDIA 驱动未安装,请到 NVIDIA 官网下载安装驱动。
python -c "import torch; print('PyTorch:', torch.__version__); print('CUDA可用:', torch.cuda.is_available()); print('显卡:', torch.cuda.get_device_name(0) if torch.cuda.is_available() else '无')"正确输出:
PyTorch: 2.6.0+cu124
CUDA可用: True
显卡: NVIDIA GeForce RTX 3060D: # 切换到 D 盘(如果已在 D 盘可跳过)
cd d:\wwwroot\modelscope
modelscope download --model AI-ModelScope/stable-diffusion-xl-base-1.0 --local_dir models/sdxl说明:
d:\wwwroot\modelscope是本教程的示例路径,请替换成你自己的项目目录。如果 CMD 当前不在 D 盘,需要先切换盘符。输入D:回车即可切换到 D 盘。
参数说明:
--model AI-ModelScope/stable-diffusion-xl-base-1.0 → 指定要下载的模型--local_dir models/sdxl → 指定下载目录模型大小约 27GB,请耐心等待下载完成。
进入 Python 交互模式:
python正确进入后显示如下:
Python 3.11.9 (tags/v3.11.9:de54cf5, Apr 2 2024, 10:12:12) [MSC v.1938 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>看到 >>> 提示符表示已进入 Python 环境,可以开始输入代码。
import torch
from diffusers import StableDiffusionXLPipeline
import osmodel_path = "models/sdxl"注意: 请将路径替换成你实际的模型存放位置,例如
"d:/wwwroot/modelscope/models/sdxl"。
pipe = StableDiffusionXLPipeline.from_pretrained(model_path, torch_dtype=torch.float16)
pipe.to("cuda")参数说明:
torch_dtype=torch.float16 → 使用半精度浮点数,节省显存,对生成效果几乎无影响pipe.to("cuda") → 将模型加载到 GPU完整执行效果示例(从导入库到加载完成):
>>> import torch
>>> from diffusers import StableDiffusionXLPipeline
>>> import os
>>> model_path = "models/sdxl"
>>> pipe = StableDiffusionXLPipeline.from_pretrained(model_path, torch_dtype=torch.float16)
Loading pipeline components...: 100%|████████| 7/7 [00:02<00:00, 2.84it/s]
>>> pipe.to("cuda")
StableDiffusionXLPipeline(...)
>>>说明:
Loading pipeline components显示模型加载进度,100% 表示加载完成 首次加载需要约 15-30 秒,取决于硬件配置 看到>>>提示符表示可以继续输入下一步
os.makedirs("pic", exist_ok=True)image = pipe("a beautiful sunset over the ocean").images[0]
image.save("pic/output.png")运行效果:
>>> image = pipe("a beautiful sunset over the ocean").images[0]
100%|████████████████████| 25/25 [00:08<00:00, 2.89it/s]
>>> image.save("pic/output.png")
>>>生成的图片质量一般,因为没有使用负面提示词和参数优化。
image = pipe(
"a cute white persian cat, fluffy long fur, blue eyes, elegant pose, lying on velvet cushion, soft indoor lighting, professional pet photography, 8k",
negative_prompt="bad anatomy, extra legs, missing legs, deformed paws, ugly, blurry, low quality, distorted face",
num_inference_steps=25
).images[0]
image.save("pic/persian_cat.png")运行效果:
>>> image = pipe(
... "a cute white persian cat, fluffy long fur, blue eyes, elegant pose, lying on velvet cushion, soft indoor lighting, professional pet photography, 8k",
... negative_prompt="bad anatomy, extra legs, missing legs, deformed paws, ugly, blurry, low quality, distorted face",
... num_inference_steps=25
... ).images[0]
100%|████████████████████| 25/25 [00:08<00:00, 2.91it/s]
>>> image.save("pic/persian_cat.png")
>>>使用负面提示词后,生成的图片质量明显提升,猫咪的肢体更加自然,细节更加精细。
参数 | 值/示例 | 作用 |
|---|---|---|
正面提示词 |
| 描述想要生成的内容:主体、细节特征、场景、光线、风格、质量词 |
|
| 要避免的内容:错误解剖结构、多余/缺失肢体、畸形、丑陋、模糊 |
|
| 推理步数,越多越精细但越慢,25 步是速度与质量的平衡点 |
|
| 提示词引导强度,越高越贴近提示词,推荐 7.0-7.5 |
告诉模型「不要」生成什么内容,可以有效减少常见缺陷。类似于给 AI 设置"禁止清单",提高生成图片的质量。
exit()或按 Ctrl+Z 然后回车。
原因: 可能是负面提示词过滤太严格,或模型加载问题
解决:
torch.float16 精度原因: 显存不足无法加载模型或生成图片
解决:
torch.float16 精度num_inference_steps(例如改为 20)# 减少推理步数
image = pipe(
prompt,
negative_prompt=negative_prompt,
num_inference_steps=20 # 从 25 减少到 20
).images[0]原因: num_inference_steps 设置太高
解决: 减少推理步数
image = pipe(
prompt,
negative_prompt=negative_prompt,
num_inference_steps=20 # 20 步已经可以生成不错的图片
).images[0]原因: Stable Diffusion 模型在生成人物手部和动物肢体时容易出错
解决方案:
负面提示词示例:
negative_prompt = "bad hands, bad fingers, extra fingers, missing fingers, bad anatomy, extra legs, deformed paws"构图技巧示例:
# 技巧 1:手插口袋
image = pipe(
"a stylish young woman, hands in pockets, casual fashion, street photography",
negative_prompt="visible hands, visible fingers, bad anatomy",
num_inference_steps=25
).images[0]
# 技巧 2:手在背后
image = pipe(
"a beautiful woman, upper body portrait, hands behind back, elegant pose",
negative_prompt="hands, fingers, bad anatomy",
num_inference_steps=25
).images[0]
# 技巧 3:远景拍摄(剪影效果)
image = pipe(
"a woman walking on beach at sunset, distant view, silhouette, golden hour",
negative_prompt="close-up hands, bad anatomy",
num_inference_steps=25
).images[0][主体描述] + [细节特征] + [场景/背景] + [光线] + [风格] + [质量词]类型 | 示例词 |
|---|---|
动物 | cute cat, fluffy dog, shiba inu, orange tabby, white rabbit, golden retriever |
毛发 | fluffy fur, soft fur, detailed fur texture, silky coat, long hair |
表情 | happy expression, cute face, big round eyes, tongue out, gentle look |
姿态 | sitting, lying down, standing, running, playing, sleeping |
场景 | in garden, on sofa, in forest, at beach, on grass, by window |
人物 | beautiful woman, young girl, asian face, handsome man |
发型 | long hair, short hair, black hair, wavy hair, blonde |
服装 | elegant dress, casual clothes, white shirt, suit, hoodie |
光线 | soft lighting, golden hour, studio lighting, natural light, warm sunlight, backlight |
风格 | portrait, realistic, professional photography, anime, cinematic, oil painting |
质量词 | high quality, detailed, 8k, masterpiece, best quality, sharp focus |
类型 | 示例词 | 作用 |
|---|---|---|
通用 | ugly, deformed, distorted, disfigured | 避免丑陋、变形 |
质量 | blurry, low quality, low resolution, jpeg artifacts | 避免模糊、低质量 |
人物手部 | bad hands, bad fingers, extra fingers, missing fingers, fused fingers | 减少手部变形 |
人物面部 | bad face, ugly face, deformed face, asymmetric eyes | 避免面部异常 |
动物肢体 | bad anatomy, extra legs, missing legs, deformed paws, extra tail | 避免动物肢体异常 |
构图 | cropped, out of frame, watermark, signature, text | 避免裁切、水印 |
# 正面:美丽女性的脸部特写、精细的脸部、完美的眼睛、柔和的光线、电影感、8K
# 负面:手、手指、身体、错误解剖、丑陋、模糊
image = pipe(
"close-up portrait of a beautiful woman, detailed face, perfect eyes, soft lighting, cinematic, 8k",
negative_prompt="hands, fingers, body, bad anatomy, ugly, blurry",
num_inference_steps=25
).images[0]
image.save("pic/face_closeup.png")# 正面:美丽的亚洲女性、黑色长发、优雅、温柔的微笑、自然妆容、影棚肖像、专业摄影、8K
# 负面:坏手、坏手指、丑陋、变形、模糊、低质量
image = pipe(
"a beautiful asian woman, long black hair, elegant, soft smile, natural makeup, studio portrait, professional photography, 8k",
negative_prompt="bad hands, bad fingers, ugly, deformed, blurry, low quality",
num_inference_steps=25
).images[0]
image.save("pic/asian_beauty.png")# 正面:动漫女孩、精美的眼睛、彩色头发、可爱的微笑、精细插画、鲜艳色彩、动漫艺术风格、高质量
# 负面:写实、照片、错误解剖、丑陋、变形、模糊
image = pipe(
"anime girl, beautiful detailed eyes, colorful hair, cute smile, detailed illustration, vibrant colors, anime art style, high quality",
negative_prompt="realistic, photo, bad anatomy, ugly, deformed, blurry",
num_inference_steps=25
).images[0]
image.save("pic/anime_girl.png")# 正面:海面上美丽的日落、黄金时刻、戴剧性的云彩、平静的波浪、水面倒影、风景摄影、鲜艳色彩、8K
# 负面:模糊、低质量、过曝
image = pipe(
"beautiful sunset over ocean, golden hour, dramatic clouds, calm waves, reflection on water, landscape photography, vivid colors, 8k",
negative_prompt="blurry, low quality, overexposed",
num_inference_steps=25
).images[0]
image.save("pic/sunset.png")# 正面:未来赛博朋克城市的夜景、霓虹灯、雨、倒影、飞行汽车、高耸的摩天大楼、银翼杀手风格、电影感、8K
# 负面:模糊、低质量、变形
image = pipe(
"futuristic cyberpunk city at night, neon lights, rain, reflections, flying cars, towering skyscrapers, blade runner style, cinematic, 8k",
negative_prompt="blurry, low quality, distorted",
num_inference_steps=25
).images[0]
image.save("pic/cyberpunk_city.png")# 正面:可爱的橘色虎斑猫、蓬松的毛发、大圆眼睛、坐在沙发上、温暖的光线、精细的毛发纹理、专业宠物摄影
# 负面:错误解剖、多余的腿、变形、丑陋、模糊
image = pipe(
"a cute orange tabby cat, fluffy fur, big round eyes, sitting on sofa, warm lighting, detailed fur texture, professional pet photography",
negative_prompt="bad anatomy, extra legs, deformed, ugly, blurry",
num_inference_steps=25
).images[0]
image.save("pic/cute_cat.png")前面介绍的交互式命令行方式适合学习和测试,但在实际使用中存在以下不便:
交互式命令行 | Python 文件方式 |
|---|---|
✗ 每次启动需要重新加载模型(耗时 15-30 秒) | ✓ 一次加载,持续生成 |
✗ 代码无法保存,关闭就丢失 | ✓ 代码保存在文件中,可重复使用 |
✗ 不支持命令快捷操作 | ✓ 支持命令快速调整参数 |
✗ 无法查看已生成的图片列表 | ✓ 内置图片管理功能 |
✗ 每次都要写完整代码 | ✓ 只需输入提示词即可 |
✗ 功能单一,难以扩展 | ✓ 支持负面提示词、步数调整等高级功能 |
结论:Python 文件方式更适合日常使用!
在项目目录下创建一个名为 image.py 的文件,例如:
d:\wwwroot\modelscope\image.py可以使用任何文本编辑器(记事本、VS Code、PyCharm 等)创建。
将以下代码保存到 image.py 文件中:
"""Stable Diffusion XL 文生图工具
功能特性:
1. 交互式输入 - 输入提示词即可生成图片
2. 负面提示词 - 自动添加常用负面提示词,也可自定义
3. 参数可调 - 可配置推理步数、引导强度等
4. 自动保存 - 图片自动保存到 pic 目录
命令:
- quit: 退出程序
- help: 显示帮助信息
- neg: 查看/修改负面提示词
- steps: 修改推理步数
- list: 列出已生成的图片
"""
import torch
import os
from diffusers import StableDiffusionXLPipeline
# ==================== 配置区 ====================
# 本地模型路径(修改为你的模型路径)
MODEL_PATH = "models/sdxl"
# 图片保存目录
OUTPUT_DIR = "pic"
# 默认负面提示词(可通过 neg 命令修改)
DEFAULT_NEGATIVE_PROMPT = "ugly, deformed, distorted, blurry, low quality, bad anatomy, extra legs, missing legs, bad hands, bad fingers, extra fingers"
# 生成参数
NUM_INFERENCE_STEPS = 25 # 推理步数,越多越精细(20-50)
GUIDANCE_SCALE = 7.5 # 引导强度,越高越贴近提示词(5-15)
# ================================================
# 创建输出目录
os.makedirs(OUTPUT_DIR, exist_ok=True)
print("正在加载模型,请稍候...")
print("(首次加载需要约 15-30 秒)")
# 加载模型
pipe = StableDiffusionXLPipeline.from_pretrained(MODEL_PATH, torch_dtype=torch.float16)
pipe.to("cuda")
print("\n模型加载完成!")
print("=" * 50)
print("输入提示词生成图片,或输入命令:")
print(" quit - 退出 | help - 帮助 | neg - 负面提示词")
print(" steps - 修改步数 | list - 已生成图片")
print("=" * 50 + "\n")
# 当前配置
current_negative_prompt = DEFAULT_NEGATIVE_PROMPT
current_steps = NUM_INFERENCE_STEPS
image_count = 0
def show_help():
"""显示帮助信息"""
print(
"""
╔══════════════════════════════════════════════════════════════╗
║ 文生图帮助 ║
╠══════════════════════════════════════════════════════════════╣
║ 直接输入提示词即可生成图片 ║
║ ║
║ 命令: ║
║ quit - 退出程序 ║
║ help - 显示本帮助 ║
║ neg - 查看当前负面提示词 ║
║ neg:xxx - 设置负面提示词(neg:blurry, ugly) ║
║ neg:reset - 重置为默认负面提示词 ║
║ steps - 查看当前推理步数 ║
║ steps:N - 设置推理步数(如 steps:30) ║
║ list - 列出已生成的图片 ║
║ ║
║ 提示词技巧: ║
║ 主体 + 细节 + 场景 + 光线 + 风格 + 质量词 ║
║ 例:a cute cat, fluffy fur, on sofa, warm light, 8k ║
╚══════════════════════════════════════════════════════════════╝
"""
)
def list_images():
"""列出已生成的图片"""
if not os.path.exists(OUTPUT_DIR):
print("[pic 目录不存在]\n")
return
files = [f for f in os.listdir(OUTPUT_DIR) if f.endswith((".png", ".jpg"))]
if not files:
print("[尚未生成任何图片]\n")
return
print(f"\n已生成 {len(files)} 张图片:")
for f in sorted(files):
filepath = os.path.join(OUTPUT_DIR, f)
size = os.path.getsize(filepath) / 1024
print(f" - {f} ({size:.1f} KB)")
print()
def generate_image(prompt: str) -> str:
"""生成图片"""
global image_count
print(f"\n正在生成...")
print(f" 提示词: {prompt[:50]}{'...' if len(prompt) > 50 else ''}")
print(f" 负面提示词: {current_negative_prompt[:30]}...")
print(f" 推理步数: {current_steps}")
# 生成图片
image = pipe(
prompt,
negative_prompt=current_negative_prompt,
num_inference_steps=current_steps,
guidance_scale=GUIDANCE_SCALE,
).images[0]
# 生成文件名
image_count += 1
filename = f"image_{image_count:03d}.png"
filepath = os.path.join(OUTPUT_DIR, filename)
# 保存
image.save(filepath)
print(f"\n✓ 图片已保存: {filepath}\n")
return filepath
# 主循环
while True:
user_input = input("提示词> ").strip()
if not user_input:
continue
# 处理命令
if user_input.lower() == "quit":
print("再见!")
break
elif user_input.lower() == "help":
show_help()
continue
elif user_input.lower() == "neg":
print(f"\n当前负面提示词:\n {current_negative_prompt}\n")
continue
elif user_input.lower().startswith("neg:"):
value = user_input[4:].strip()
if value.lower() == "reset":
current_negative_prompt = DEFAULT_NEGATIVE_PROMPT
print("[已重置为默认负面提示词]\n")
else:
current_negative_prompt = value
print(f"[负面提示词已更新为: {value[:50]}...]\n")
continue
elif user_input.lower() == "steps":
print(f"\n当前推理步数: {current_steps}\n")
continue
elif user_input.lower().startswith("steps:"):
try:
value = int(user_input[6:].strip())
if 10 <= value <= 100:
current_steps = value
print(f"[推理步数已设置为: {value}]\n")
else:
print("[步数应在 10-100 之间]\n")
except ValueError:
print("[无效的步数,请输入数字]\n")
continue
elif user_input.lower() == "list":
list_images()
continue
# 生成图片
try:
generate_image(user_input)
except Exception as e:
print(f"\n[生成失败: {e}]\n")打开命令提示符(CMD),进入项目目录:
注意: 如果 CMD 当前不在 D 盘,需要先切换盘符。输入
D:回车即可切换到 D 盘。
D: # 切换到 D 盘(如果已在 D 盘可跳过)
cd d:\wwwroot\modelscope
python image.py正在加载模型,请稍候...
(首次加载需要约 15-30 秒)
模型加载完成!
==================================================
输入提示词生成图片,或输入命令:
quit - 退出 | help - 帮助 | neg - 负面提示词
steps - 修改步数 | list - 已生成图片
==================================================
提示词> a cute cat, fluffy fur, on sofa, warm lighting, 8k
正在生成...
提示词: a cute cat, fluffy fur, on sofa, warm lighting, 8k
负面提示词: ugly, deformed, distorted...
推理步数: 25
✓ 图片已保存: pic\image_001.png
提示词>1. 查看帮助
提示词> help
╔══════════════════════════════════════════════════════════════╗
║ 文生图帮助 ║
╠══════════════════════════════════════════════════════════════╣
║ 直接输入提示词即可生成图片 ║
║ ║
║ 命令: ║
║ quit - 退出程序 ║
║ help - 显示本帮助 ║
║ neg - 查看当前负面提示词 ║
║ neg:xxx - 设置负面提示词(neg:blurry, ugly) ║
║ neg:reset - 重置为默认负面提示词 ║
║ steps - 查看当前推理步数 ║
║ steps:N - 设置推理步数(如 steps:30) ║
║ list - 列出已生成的图片 ║
║ ║
║ 提示词技巧: ║
║ 主体 + 细节 + 场景 + 光线 + 风格 + 质量词 ║
║ 例:a cute cat, fluffy fur, on sofa, warm light, 8k ║
╚══════════════════════════════════════════════════════════════╝2. 查看当前负面提示词
提示词> neg
当前负面提示词:
ugly, deformed, distorted, blurry, low quality, bad anatomy, extra legs, missing legs, bad hands, bad fingers, extra fingers3. 修改负面提示词
提示词> neg:blurry, ugly, low quality
[负面提示词已更新为: blurry, ugly, low quality]4. 重置负面提示词
提示词> neg:reset
[已重置为默认负面提示词]5. 查看当前推理步数
提示词> steps
当前推理步数: 256. 修改推理步数
提示词> steps:30
[推理步数已设置为: 30]7. 查看已生成的图片
提示词> list
已生成 3 张图片:
- image_001.png (1234.5 KB)
- image_002.png (1156.8 KB)
- image_003.png (1298.3 KB)8. 退出程序
提示词> quit
再见!代码开头的配置区域可以根据需要修改:
# ==================== 配置区 ====================
# 本地模型路径
MODEL_PATH = "models/sdxl"
# 图片保存目录
OUTPUT_DIR = "pic"
# 默认负面提示词
DEFAULT_NEGATIVE_PROMPT = "ugly, deformed, distorted, blurry, low quality, bad anatomy, extra legs, missing legs, bad hands, bad fingers, extra fingers"
# 生成参数
NUM_INFERENCE_STEPS = 25 # 推理步数(20-50)
GUIDANCE_SCALE = 7.5 # 引导强度(5-15)
# ================================================配置项 | 说明 | 推荐值 |
|---|---|---|
| 模型路径 |
|
| 图片保存目录 |
|
| 默认负面提示词 | 见上文常用词汇 |
| 默认推理步数,越多越精细但越慢 | 25 |
| 提示词引导强度,越高越符合提示词 | 7.5 |
你可以修改 DEFAULT_NEGATIVE_PROMPT 来设置不同场景的默认负面提示词:
# 人物肖像专用
DEFAULT_NEGATIVE_PROMPT = "bad hands, bad fingers, extra fingers, missing fingers, deformed hands, ugly, blurry, low quality, bad face, asymmetric eyes"
# 动物专用
DEFAULT_NEGATIVE_PROMPT = "bad anatomy, extra legs, missing legs, deformed paws, extra tail, ugly, blurry, low quality, distorted"
# 风景专用
DEFAULT_NEGATIVE_PROMPT = "blurry, low quality, overexposed, underexposed, distorted, ugly"
# 动漫专用
DEFAULT_NEGATIVE_PROMPT = "realistic, photo, bad anatomy, ugly, deformed, blurry, low quality, bad hands, extra fingers"原因: 未安装 diffusers 库
解决:
pip install "diffusers>=0.36.0" -i https://mirrors.aliyun.com/pypi/simple/原因: MODEL_PATH 设置错误
解决: 修改代码中的 MODEL_PATH 为你实际的模型路径
MODEL_PATH = "你的模型路径/sdxl"原因: 可能是负面提示词过滤太严格,或模型加载问题
解决:
neg:resetneg:blurry, low quality解决方案:
steps:20torch.float16 精度(代码中已默认使用)原因: 推理步数过多
解决: 减少推理步数
提示词> steps:2020 步已经可以生成不错的图片,25-30 步是平衡点。
如果想生成多张相似的图片,可以多次输入相同或相似的提示词:
提示词> a cute cat, fluffy fur, on sofa, 8k
✓ 图片已保存: pic\image_001.png
提示词> a cute cat, fluffy fur, on sofa, 8k
✓ 图片已保存: pic\image_002.png
提示词> a cute cat, fluffy fur, on sofa, 8k
✓ 图片已保存: pic\image_003.png每次生成的图片都会略有不同(随机种子不同)。
为不同场景设置专用的负面提示词:
# 生成人物
提示词> neg:bad hands, bad fingers, ugly, blurry
提示词> a beautiful woman, elegant dress, 8k
# 切换到风景
提示词> neg:blurry, low quality
提示词> beautiful mountain landscape, sunset, 8k
# 切换到动物
提示词> neg:bad anatomy, extra legs, ugly, blurry
提示词> a cute dog, fluffy fur, 8k如果觉得图片质量不够好:
提示词> steps:35
[推理步数已设置为: 35]更多步数 = 更精细的图片,但生成时间更长。
如果想让 AI 更严格遵循提示词,可以修改代码中的 GUIDANCE_SCALE:
GUIDANCE_SCALE = 9.0 # 默认 7.5,越高越严格遵循提示词5.0-7.0:更自由、更有创意7.0-9.0:平衡9.0-15.0:严格遵循提示词,但可能过饱和1. 启动程序
python image.py
2. 设置人物专用负面提示词
提示词> neg:bad hands, bad fingers, ugly, deformed, blurry, low quality
3. 生成图片
提示词> a beautiful asian woman, long black hair, elegant, soft smile, professional photography, 8k
✓ 图片已保存: pic\image_001.png
4. 查看结果,如果不满意调整参数
提示词> steps:30
提示词> a beautiful asian woman, long black hair, elegant, soft smile, professional photography, 8k
✓ 图片已保存: pic\image_002.png1. 设置风景专用负面提示词
提示词> neg:blurry, low quality, overexposed
2. 生成多张风景
提示词> beautiful mountain landscape at sunset, golden hour, 8k
提示词> forest path with sunlight, green trees, peaceful, 8k
提示词> ocean waves at sunrise, dramatic sky, 8k
3. 查看已生成的图片
提示词> list1. 设置动漫专用负面提示词
提示词> neg:realistic, photo, bad anatomy, ugly, deformed
2. 生成动漫角色
提示词> anime girl, colorful hair, cute smile, detailed eyes, vibrant colors, anime art style, high quality
✓ 图片已保存: pic\image_001.png恭喜!到这里你已经掌握了基于 ModelScope 本地部署 Stable Diffusion XL AI 绘画模型的完整流程。
我们从零开始,依次完成了以下关键步骤:
完成本教程后,一般来说将能够:
✅ 独立部署 AI 绘画模型:掌握从环境配置到模型运行的完整流程
✅ 使用 ModelScope 平台:熟悉魔搭社区的模型下载和管理方式
✅ 配置 GPU 加速:理解 CUDA 原理,正确安装和验证 PyTorch
✅ 排查常见错误:处理环境问题、显存不足、图片质量等问题
✅ 编写高质量提示词:掌握正面和负面提示词的编写技巧
✅ 开发图片生成应用:创建支持交互式操作、命令系统的 AI 绘图工具
✅ 自定义模型行为:通过参数调整控制生成效果和质量
✅ 优化生成性能:调整推理步数、使用量化技术降低资源消耗
基于实际测试,Stable Diffusion XL 模型在不同场景下的表现各有差异:
场景适用性评估:
场景 | 推荐程度 | 生成效果 | 使用建议 |
|---|---|---|---|
风景图 | ⭐⭐⭐⭐⭐ | 优秀 | 色彩饱和、构图自然,可直接生成,质量稳定 |
动漫插画 | ⭐⭐⭐⭐⭐ | 优秀 | 风格统一、线条流畅,适合二次元创作 |
人物肖像(脸部) | ⭐⭐⭐⭐ | 良好 | 面部细节精细,建议使用脸部特写,配合负面提示词 |
动物宠物 | ⭐⭐⭐⭐ | 良好 | 毛发纹理真实,注意控制肢体数量,配合负面提示词 |
手部特写 | ⭐ | 较差 | 容易变形,建议使用构图技巧隐藏(见第八章) |
混合场景 | ⭐⭐⭐⭐ | 良好 | 人物+风景时,人物作为主体,风景作为背景 |
如果想进一步提升,可以尝试:
希望这篇教程能帮助你顺利部署属于自己的 AI 绘画模型!如果遇到问题,欢迎反馈和交流。
祝你在 AI 绘画领域不断探索,创作出精彩的作品! 🎨
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。