AI 绘画的核心不是“输入提示词等一张图”,而是理解扩散模型如何从噪声中重建图像,以及如何用条件控制生成过程。本文从原理、提示词、LoRA、ControlNet 到工程化,给出可运行代码和关键要点。
扩散模型分两个过程:前向加噪和反向去噪。训练时对真实图像逐步加高斯噪声,模型学习预测每一步的噪声;推理时从纯噪声出发,逐步去噪生成图像。
import torch
def forward_diffusion(x0, t, noise, alphas_cumprod):
"""前向过程:对原图加噪"""
a = alphas_cumprod[t].sqrt()
b = (1 - alphas_cumprod[t]).sqrt()
return a * x0 + b * noise
def sample_timesteps(batch_size, total_steps):
return torch.randint(0, total_steps, (batch_size,))Stable Diffusion 在其上引入潜在空间:先用 VAE 把图像压缩到低维 latent,在 latent 上做扩散,最后解码回像素。这让推理成本大幅降低。
import torch
from diffusers import StableDiffusionXLPipeline
pipe = StableDiffusionXLPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
torch_dtype=torch.float16,
variant="fp16",
).to("cuda")
prompt = ("cinematic portrait of a young woman in a rainy Tokyo street, "
"85mm lens, f/1.4, soft rim light, film grain, high detail")
negative = "lowres, blurry, extra fingers, watermark, text"
image = pipe(
prompt=prompt,
negative_prompt=negative,
num_inference_steps=30,
guidance_scale=7.5,
width=1024,
height=1024,
).images[0]
image.save("aigc.png")关键参数:
num_inference_steps:步数越多越精细,但边际收益递减;guidance_scale:提示词遵循强度,通常 7—8.5,太高会过饱和;negative_prompt:排除畸形、水印、低质量。AI 不懂“美”,但懂参数。五维构建法:主体 + 动作 + 环境 + 样式 + 画质。
def build_prompt(subject, action, env, style, quality):
return f"{subject}, {action}, {env}, {style}, {quality}"
prompt = build_prompt(
subject="a young woman",
action="leaning by a window, soft gaze",
env="gray studio background, marble table",
style="Rembrandt lighting, 85mm, f/1.4, Kodak Portra 400",
quality="ultra detailed, natural skin, film grain",
)易错点:
镜头语言、光位、胶片模拟是最可控的风格变量。
通用模型很难每次都生成同一种摄影语言。LoRA 冻结基座,注入低秩矩阵,只训练少量参数。
同一风格 20—50 张,覆盖多角度、多光位。清洗去水印,统一分辨率并打标:
import os
TAG = "mystyle, 85mm, f/1.4, Rembrandt lighting, Kodak Portra 400, shallow dof"
for f in os.listdir("train"):
if f.endswith(".jpg"):
with open(f"train/{f[:-4]}.txt", "w") as fp:
fp.write(TAG)加入 5%—10% 通用图做正则化,防止过拟合。
accelerate launch train_text_to_image_lora_sdxl.py \
--pretrained_model_name_or_path="stabilityai/stable-diffusion-xl-base-1.0" \
--train_data_dir="./photos" \
--output_dir="./lora-photo" \
--resolution=1024 \
--train_batch_size=1 \
--gradient_accumulation_steps=4 \
--learning_rate=1e-4 \
--lr_scheduler="cosine" \
--max_train_steps=2000 \
--rank=32 \
--mixed_precision="fp16"推荐:rank 16—32,学习率 1e-4,epoch 10—20。步数太多会“只会复读训练图”。
pipe.load_lora_weights("./lora-photo",
weight_name="pytorch_lora_weights.safetensors")
pipe.fuse_lora(lora_scale=0.8) # 0.6–0.9 较自然LoRA 控制风格,ControlNet 控制结构。常用条件:Canny 边缘、OpenPose 骨架、Depth 深度、Scribble 涂鸦。
from diffusers import ControlNetModel, StableDiffusionXLControlNetPipeline
from PIL import Image
controlnet = ControlNetModel.from_pretrained(
"diffusers/controlnet-canny-sdxl-1.0",
torch_dtype=torch.float16,
).to("cuda")
pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
controlnet=controlnet,
torch_dtype=torch.float16,
).to("cuda")
image = pipe(
prompt="a cyberpunk warrior, neon light, cinematic",
image=Image.open("pose.png"), # 条件图
controlnet_conditioning_scale=0.8,
num_inference_steps=30,
).images[0]controlnet_conditioning_scale 控制结构约束强度,太高会失去生成自由度。
批量生产:封装推理函数,加入种子、尺寸、参数记录,便于复现。
评测:固定 prompt、盲测、一致性打分,维度包括构图、光影、色彩、风格一致性。
合规底线:数据授权链清晰;禁止生成侵权 IP 与真实名人肖像;输出添加“AI生成”标识并嵌入不可篡改水印;高风险内容人工审核。
AI 绘画的完整链路:扩散原理 → 推理调用 → 提示词 → LoRA → ControlNet → 工程化。模型能力只是起点,真正决定出片质量的是数据质量、标注一致性和你的审美判断。掌握这条链路,才能从“抽卡”走向可控生产。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。