Skip to content

从零开始:基于 ModelScope 本地部署 Stable Diffusion XL AI 绘画完全指南

约 6976 字大约 23 分钟

AIStable DiffusionSDXLAI绘画

2026-01-11

本文档记录了使用魔搭社区 ModelScope 平台,从零开始在本地部署 Stable Diffusion XL(SDXL)AI 绘画模型的完整过程,包括环境配置、依赖安装、模型下载、提示词编写技巧以及实战示例。

关于 ModelScope: ModelScope 社区是一个模型开源社区及创新平台,由阿里巴巴通义实验室,联合 CCF 开源发展技术委员会,共同作为项目发起创建。(摘自官方文档)


前置准备:安装 Python(如果未安装)

0.1 检查是否已安装 Python

打开命令提示符(CMD),输入:

python --version
  • 如果显示版本号(如 Python 3.11.9)→ 已安装,跳到「一、测试环境」
  • 如果提示「不是内部或外部命令」 → 未安装,继续下面步骤

0.2 下载 Python

  1. 访问 Python 官网:https://www.python.org/downloads/
  2. 点击 Download Python 3.11.x(推荐 3.10 或 3.11 版本)
  3. 下载 Windows 安装包(约 25MB)

0.3 安装 Python

  1. 双击运行下载的安装包
  2. 重要! 勾选底部的 「Add Python to PATH」(添加到环境变量)
  3. 点击 Install Now 开始安装
  4. 等待安装完成,点击 Close

0.4 验证安装

关闭并重新打开命令提示符,输入:

python --version

显示版本号即安装成功:

Python 3.11.9

0.5 验证 pip(Python 包管理器)

pip --version

显示类似以下内容即正常:

pip 24.0 from D:\Program Files\Python311\Lib\site-packages\pip (python 3.11)

0.6 常见问题

问题:安装后仍提示「不是内部命令」

原因: 安装时没有勾选「Add Python to PATH」

解决方案 1:重新安装

  1. 卸载 Python(控制面板 → 程序和功能)
  2. 重新运行安装包,务必勾选 Add Python to PATH

解决方案 2:手动添加环境变量

  1. 右键「此电脑」→ 属性 → 高级系统设置 → 环境变量
  2. 在「系统变量」中找到 Path,点击编辑
  3. 添加 Python 安装路径,例如:
    • D:\Program Files\Python311\
    • D:\Program Files\Python311\Scripts\
  4. 确定保存,重新打开 CMD

一、环境信息

说明: 以下是博主个人电脑的配置环境,本文档所有操作和测试结果均基于此环境。不同的硬件配置可能会有不同的表现,仅供参考。

项目配置
操作系统Windows 10
Python 版本3.11.9
显卡NVIDIA GeForce RTX 3060 (12GB 显存)
CUDA 版本12.4
PyTorch2.6.0+cu124
模型Stable Diffusion XL Base 1.0

二、安装依赖

2.1 安装 ModelScope

官网写法:

pip install modelscope

推荐写法(国内用户):

pip install modelscope -i https://mirrors.aliyun.com/pypi/simple/

两者区别:

命令下载来源速度
pip install modelscopePyPI 官方源(国外服务器)国内较慢
pip install modelscope -i 镜像地址国内镜像服务器快很多

-i--index-url 的缩写,用于指定下载源。安装的包完全相同,只是下载速度不同。

2.2 安装 PyTorch(CUDA 版本)

重要:必须安装 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

遇到的问题:安装了 CPU 版本的 PyTorch

如何检查? 运行以下命令验证:

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 版本
  • 阿里云镜像没有 CUDA 版本的 PyTorch
  • PyTorch CUDA 版本托管在 PyTorch 官方服务器

解决方案:

第一步:卸载错误的 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 即修复成功。

2.3 安装 Diffusers

pip install "diffusers>=0.36.0" -i https://mirrors.aliyun.com/pypi/simple/

核心库的作用:

库名作用
torchPyTorch 深度学习框架,模型运行的"引擎"
diffusers扩散模型库,提供 SDXL 模型加载和推理

三、验证环境

3.1 验证 Python

python --version
# 输出: Python 3.11.9

3.2 验证显卡

nvidia-smi

正常会显示显卡型号、驱动版本、显存使用情况等信息。

如果提示「不是内部或外部命令」,说明 NVIDIA 驱动未安装,请到 NVIDIA 官网下载安装驱动。

3.3 验证 PyTorch CUDA

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 3060

四、下载模型

4.1 使用命令行下载

D:                          # 切换到 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 环境,可以开始输入代码。

5.1 导入库

import torch
from diffusers import StableDiffusionXLPipeline
import os

5.2 指定模型路径

model_path = "models/sdxl"

注意: 请将路径替换成你实际的模型存放位置,例如 "d:/wwwroot/modelscope/models/sdxl"

5.3 加载模型到 GPU

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 秒,取决于硬件配置
  • 看到 >>> 提示符表示可以继续输入下一步

5.4 创建图片保存目录

os.makedirs("pic", exist_ok=True)

六、生成图片

6.1 基础用法(不推荐)

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")
>>>

生成的图片质量一般,因为没有使用负面提示词和参数优化。


6.2 推荐用法(带负面提示词)

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")
>>>

使用负面提示词后,生成的图片质量明显提升,猫咪的肢体更加自然,细节更加精细。


6.3 参数说明

参数值/示例作用
正面提示词"a cute white persian cat, fluffy long fur..."描述想要生成的内容:主体、细节特征、场景、光线、风格、质量词
negative_prompt"bad anatomy, extra legs, missing legs..."要避免的内容:错误解剖结构、多余/缺失肢体、畸形、丑陋、模糊
num_inference_steps25(推荐 20-30)推理步数,越多越精细但越慢,25 步是速度与质量的平衡点
guidance_scale7.5(可选,默认 7.5)提示词引导强度,越高越贴近提示词,推荐 7.0-7.5

6.4 负面提示词的作用

告诉模型「不要」生成什么内容,可以有效减少常见缺陷。类似于给 AI 设置"禁止清单",提高生成图片的质量。


七、退出 Python

exit()

或按 Ctrl+Z 然后回车。


八、常见问题和解决方案

问题 1:生成的图片为黑色

原因: 可能是负面提示词过滤太严格,或模型加载问题

解决:

  1. 尝试减少负面提示词
  2. 检查模型文件是否完整下载
  3. 确保使用了 torch.float16 精度

问题 2:显存不足(Out of Memory)

原因: 显存不足无法加载模型或生成图片

解决:

  1. 确保使用了 torch.float16 精度
  2. 减少 num_inference_steps(例如改为 20)
  3. 关闭其他占用显存的程序
# 减少推理步数
image = pipe(
    prompt,
    negative_prompt=negative_prompt,
    num_inference_steps=20  # 从 25 减少到 20
).images[0]

问题 3:生成速度太慢

原因: num_inference_steps 设置太高

解决: 减少推理步数

image = pipe(
    prompt,
    negative_prompt=negative_prompt,
    num_inference_steps=20  # 20 步已经可以生成不错的图片
).images[0]

问题 4:手部或肢体变形

原因: Stable Diffusion 模型在生成人物手部和动物肢体时容易出错

解决方案:

  1. 在负面提示词中添加相关关键词
  2. 避免手部特写,使用构图技巧隐藏手部

负面提示词示例:

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避免裁切、水印

十、示例提示词

1. 人物肖像(脸部特写)

# 正面:美丽女性的脸部特写、精细的脸部、完美的眼睛、柔和的光线、电影感、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")

2. 亚洲美女

# 正面:美丽的亚洲女性、黑色长发、优雅、温柔的微笑、自然妆容、影棚肖像、专业摄影、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")

3. 动漫风格

# 正面:动漫女孩、精美的眼睛、彩色头发、可爱的微笑、精细插画、鲜艳色彩、动漫艺术风格、高质量
# 负面:写实、照片、错误解剖、丑陋、变形、模糊
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")

4. 风景 - 日落海滩

# 正面:海面上美丽的日落、黄金时刻、戴剧性的云彩、平静的波浪、水面倒影、风景摄影、鲜艳色彩、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")

5. 科幻城市

# 正面:未来赛博朋克城市的夜景、霓虹灯、雨、倒影、飞行汽车、高耸的摩天大楼、银翼杀手风格、电影感、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")

6. 可爱动物

# 正面:可爱的橘色虎斑猫、蓬松的毛发、大圆眼睛、坐在沙发上、温暖的光线、精细的毛发纹理、专业宠物摄影
# 负面:错误解剖、多余的腿、变形、丑陋、模糊
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 文件进行图片生成(推荐)

11.1 为什么使用 Python 文件更方便?

前面介绍的交互式命令行方式适合学习和测试,但在实际使用中存在以下不便:

交互式命令行Python 文件方式
✗ 每次启动需要重新加载模型(耗时 15-30 秒)✓ 一次加载,持续生成
✗ 代码无法保存,关闭就丢失✓ 代码保存在文件中,可重复使用
✗ 不支持命令快捷操作✓ 支持命令快速调整参数
✗ 无法查看已生成的图片列表✓ 内置图片管理功能
✗ 每次都要写完整代码✓ 只需输入提示词即可
✗ 功能单一,难以扩展✓ 支持负面提示词、步数调整等高级功能

结论:Python 文件方式更适合日常使用!


11.2 准备工作

创建 Python 文件

在项目目录下创建一个名为 image.py 的文件,例如:

d:\wwwroot\modelscope\image.py

可以使用任何文本编辑器(记事本、VS Code、PyCharm 等)创建。


11.3 完整代码

将以下代码保存到 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")

11.4 运行 Python 文件

打开命令提示符(CMD),进入项目目录:

注意: 如果 CMD 当前不在 D 盘,需要先切换盘符。输入 D: 回车即可切换到 D 盘。

D:                          # 切换到 D 盘(如果已在 D 盘可跳过)
cd d:\wwwroot\modelscope
python image.py

11.5 使用说明

基本操作

正在加载模型,请稍候...
(首次加载需要约 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 fingers

3. 修改负面提示词

提示词> neg:blurry, ugly, low quality
[负面提示词已更新为: blurry, ugly, low quality]

4. 重置负面提示词

提示词> neg:reset
[已重置为默认负面提示词]

5. 查看当前推理步数

提示词> steps

当前推理步数: 25

6. 修改推理步数

提示词> 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
再见!

11.6 自定义配置

代码开头的配置区域可以根据需要修改:

# ==================== 配置区 ====================
# 本地模型路径
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)
# ================================================

配置说明

配置项说明推荐值
MODEL_PATH模型路径"models/sdxl"
OUTPUT_DIR图片保存目录"pic"
DEFAULT_NEGATIVE_PROMPT默认负面提示词见上文常用词汇
NUM_INFERENCE_STEPS默认推理步数,越多越精细但越慢25
GUIDANCE_SCALE提示词引导强度,越高越符合提示词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"

11.7 常见问题

问题 1:提示「ModuleNotFoundError: No module named 'diffusers'」

原因: 未安装 diffusers 库

解决:

pip install "diffusers>=0.36.0" -i https://mirrors.aliyun.com/pypi/simple/

问题 2:提示「找不到模型路径」

原因: MODEL_PATH 设置错误

解决: 修改代码中的 MODEL_PATH 为你实际的模型路径

MODEL_PATH = "你的模型路径/sdxl"

问题 3:生成黑色图片

原因: 可能是负面提示词过滤太严格,或模型加载问题

解决:

  1. 尝试重置负面提示词:neg:reset
  2. 尝试减少负面提示词:neg:blurry, low quality
  3. 检查模型文件是否完整下载

问题 4:显存不足(Out of Memory)

解决方案:

  1. 减少推理步数:steps:20
  2. 确保使用了 torch.float16 精度(代码中已默认使用)
  3. 关闭其他占用显存的程序

问题 5:生成速度太慢

原因: 推理步数过多

解决: 减少推理步数

提示词> steps:20

20 步已经可以生成不错的图片,25-30 步是平衡点。


11.8 进阶技巧

技巧 1:批量生成

如果想生成多张相似的图片,可以多次输入相同或相似的提示词:

提示词> 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

每次生成的图片都会略有不同(随机种子不同)。

技巧 2:快速切换场景

为不同场景设置专用的负面提示词:

# 生成人物
提示词> 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

技巧 3:精细调整生成质量

如果觉得图片质量不够好:

提示词> steps:35
[推理步数已设置为: 35]

更多步数 = 更精细的图片,但生成时间更长。

技巧 4:修改引导强度

如果想让 AI 更严格遵循提示词,可以修改代码中的 GUIDANCE_SCALE

GUIDANCE_SCALE = 9.0  # 默认 7.5,越高越严格遵循提示词
  • 5.0-7.0:更自由、更有创意
  • 7.0-9.0:平衡
  • 9.0-15.0:严格遵循提示词,但可能过饱和

11.9 实用工作流示例

工作流 1:生成人物肖像

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.png

工作流 2:生成风景图

1. 设置风景专用负面提示词
提示词> 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. 查看已生成的图片
提示词> list

工作流 3:生成动漫角色

1. 设置动漫专用负面提示词
提示词> 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 绘画模型的完整流程。

本教程内容回顾

我们从零开始,依次完成了以下关键步骤:

  1. 环境准备:安装 Python、配置环境变量
  2. 依赖安装:ModelScope、PyTorch CUDA 版、Diffusers 等核心库
  3. 环境验证:检查 Python、显卡、CUDA 是否配置正确
  4. 模型下载:使用 ModelScope 命令行工具下载 SDXL 模型(约 27GB)
  5. 模型加载:在 Python 交互式环境中加载并测试模型
  6. 图片生成:使用提示词和负面提示词生成高质量图片
  7. 问题解决:处理常见错误,如显存不足、黑色图片、手部变形等
  8. 提示词技巧:掌握正面和负面提示词的编写方法
  9. 实用工具:创建 Python 文件,实现交互式图片生成、命令管理等功能
  10. 高级配置:自定义负面提示词、调整生成参数、优化显存占用

学习掌握的能力

完成本教程后,一般来说将能够:

独立部署 AI 绘画模型:掌握从环境配置到模型运行的完整流程
使用 ModelScope 平台:熟悉魔搭社区的模型下载和管理方式
配置 GPU 加速:理解 CUDA 原理,正确安装和验证 PyTorch
排查常见错误:处理环境问题、显存不足、图片质量等问题
编写高质量提示词:掌握正面和负面提示词的编写技巧
开发图片生成应用:创建支持交互式操作、命令系统的 AI 绘图工具
自定义模型行为:通过参数调整控制生成效果和质量
优化生成性能:调整推理步数、使用量化技术降低资源消耗

适用场景与应用方向

基于实际测试,Stable Diffusion XL 模型在不同场景下的表现各有差异:

场景适用性评估:

场景推荐程度生成效果使用建议
风景图⭐⭐⭐⭐⭐优秀色彩饱和、构图自然,可直接生成,质量稳定
动漫插画⭐⭐⭐⭐⭐优秀风格统一、线条流畅,适合二次元创作
人物肖像(脸部)⭐⭐⭐⭐良好面部细节精细,建议使用脸部特写,配合负面提示词
动物宠物⭐⭐⭐⭐良好毛发纹理真实,注意控制肢体数量,配合负面提示词
手部特写较差容易变形,建议使用构图技巧隐藏(见第八章)
混合场景⭐⭐⭐⭐良好人物+风景时,人物作为主体,风景作为背景

后续学习建议

如果想进一步提升,可以尝试:

  • 探索其他模型:在 ModelScope 上尝试 SDXL-Turbo(更快)、Stable Diffusion 3(更新)等模型
  • 学习 LoRA 微调:使用自己的数据集训练 LoRA,打造个性化风格
  • 集成到应用:将模型集成到 Web 应用、聊天机器人、自动化工具中
  • 探索 ControlNet:使用边缘检测、姿态估计等技术精确控制生成结果
  • 研究提示词工程:深入学习提示词权重、混合、分步生成等高级技巧

感谢阅读

希望这篇教程能帮助你顺利部署属于自己的 AI 绘画模型!如果遇到问题,欢迎反馈和交流。

祝你在 AI 绘画领域不断探索,创作出精彩的作品! 🎨