AI绘图常被简化为“写提示词、等图出来”。但同一句提示词生成十次,十张图细节各不相同;换一个模型,风格完全漂移;想固定一个角色跨十张图使用,几乎做不到。这些问题的根源不在提示词写得不够好,而在于 AI绘图本质是在高维图像空间中采样一个条件分布:p(x|c),条件 c 可以包含文本、姿态、深度、参考图、风格 LoRA。
这意味着专业工程要解决三件事:条件如何精确注入(文本之外的 ControlNet、IP-Adapter、LoRA)、采样如何可控(CFG、步数、调度器、种子)、结果如何可复现与可评估(参数留痕、批量筛选、三维指标)。只会调提示词,就是在分布里碰运气;理解了条件与采样,才能稳定产出。
提示词层:正向/负向提示,最基础但最不可控。同一词在不同模型权重下语义漂移。
结构控制层:ControlNet(Canny、Depth、OpenPose、Lineart),把空间结构作为条件从旁路注入,实现“按线稿上色”“按姿态生成”。
风格控制层:LoRA 低秩适配器,只训练原权重 0.1%–1% 的参数,切换风格不换主模型。
参考控制层:IP-Adapter,用参考图特征替代或叠加文本条件,实现“角色一致性”。
区域控制层:Inpainting + 蒙版,局部重绘而非全图重生成,是商业修图的核心操作。
角色一致性。 同一角色跨图保持一致,是商业应用的第一道关。纯提示词做不到。解法是 IP-Adapter 参考图 + 角色 LoRA + 固定种子 三者叠加,且参考图需去背景、统一光照。
分辨率与细节。 直接生成 2048×2048 会崩(模型训练分辨率通常是 1024)。正确做法是 基础生成 1024 + 放大模型精修 + 局部 Inpainting 补细节,分两到三步走,而非一步到位。
可复现与批量筛选。 出了好图却记不住种子和参数,等于白做。生产流程必须全参数留痕 + 批量生成 + 自动质检筛选,人工只看通过筛选的图。
(1)基础采样:CFG 与种子控制
import torch
@torch.no_grad()
def generate(unet, vae, text_emb, uncond_emb, shape,
seed=42, steps=30, guidance=7.5):
"""固定种子 + CFG 引导:可复现的基础生成"""
g = torch.Generator(device="cuda").manual_seed(seed)
x = torch.randn(shape, device="cuda", generator=g)
ts = torch.linspace(999, 0, steps + 1).long().cuda()
for i in range(steps):
t, tp = ts[i], ts[i + 1]
eps_c = unet(x, t, encoder_hidden_states=text_emb).sample
eps_u = unet(x, t, encoder_hidden_states=uncond_emb).sample
eps = eps_u + guidance * (eps_c - eps_u) # CFG:放大条件差
a_t, a_p = alpha_bar(t), alpha_bar(tp)
x0 = ((x - (1 - a_t).sqrt() * eps) / a_t.sqrt()).clamp(-1, 1)
x = a_p.sqrt() * x0 + (1 - a_p).sqrt() * eps
return vae.decode(x / 0.18215).sample(2)ControlNet:结构条件旁路注入
class ControlNetBranch:
"""零初始化旁路:训练初期不影响主模型,逐步学习结构条件"""
def __init__(self, encoder_blocks, cond_ch=3):
self.proj = torch.nn.Conv2d(cond_ch, encoder_blocks[0].ch, 3, padding=1)
self.blocks = torch.nn.ModuleList(
[type(b)(b) for b in encoder_blocks])
self.zero = torch.nn.ModuleList(
[torch.nn.Conv2d(b.ch, b.ch, 1) for b in encoder_blocks])
for z in self.zero: # 零初始化是关键
torch.nn.init.zeros_(z.weight)
torch.nn.init.zeros_(z.bias)
def __call__(self, cond, hiddens):
h = self.proj(cond); outs = []
for blk, z, hh in zip(self.blocks, self.zero, hiddens):
h = blk(h)
outs.append(z(h) + hh) # 残差叠加到主模型中间层
return outs
# 用法:Canny/Depth/OpenPose 图作为 cond,实现“按结构生成”(3)IP-Adapter 参考图:角色一致性
class IPAdapter:
"""把参考图特征注入交叉注意力,实现角色/风格一致性"""
def __init__(self, image_encoder, proj, scale=0.8):
self.encoder = image_encoder
self.proj = proj # 映射到文本嵌入空间
self.scale = scale
def condition(self, ref_image, text_emb):
img_feat = self.encoder(ref_image).unsqueeze(1) # [1,1,D]
img_feat = self.proj(img_feat) * self.scale
# 拼在文本嵌入前面,注意力同时看到参考图与文本
return torch.cat([img_feat, text_emb], dim=1)
# 验收:同角色跨5张图,DINOv2相似度>0.85(4)Inpainting:局部重绘
@torch.no_grad()
def inpaint(unet, vae, image, mask, text_emb, steps=25, guidance=7.0):
"""蒙版区域去噪,其余区域每一步都回填原图,实现局部重绘"""
latent = vae.encode(image).latent_dist.sample() * 0.18215
m = torch.nn.functional.interpolate(mask, size=latent.shape[-2:])
x = latent * (1 - m) + torch.randn_like(latent) * m
ts = torch.linspace(999, 0, steps + 1).long().cuda()
for i in range(steps):
t = ts[i].expand(x.shape[0])
eps = unet(x, t, encoder_hidden_states=text_emb).sample
a_t = alpha_bar(t).view(-1, 1, 1, 1)
x0 = ((x - (1 - a_t).sqrt() * eps) / a_t.sqrt()).clamp(-1, 1)
# 关键:蒙版外强制回填原latent,保证未编辑区域完全不变
x = x0 * m + latent * (1 - m)
return vae.decode(x / 0.18215).sample(5)两阶段放大:基础生成 + 精修
def hires_generate(base_unet, upscaler, vae, emb, shape,
scale=2, denoise=0.45, seed=42):
"""直接出高分辨率会崩,正确做法是基础生成后做带降噪的放大精修"""
img = generate(base_unet, vae, emb, emb, shape, seed=seed)
img_up = upscaler(img, scale=scale) # ESRGAN/4x-UltraSharp 类
# 二次采样:低降噪强度,只在放大图上补细节,不改变整体构图
return generate(base_unet, vae, emb, emb,
(1, 4, *img_up.shape[-2:]), seed=seed + 1,
steps=20, guidance=denoise * 10)(6)参数留痕与批量质检
import hashlib, json, numpy as np
from PIL import Image
def fingerprint(prompt, neg, seed, model, cfg, control=None) -> str:
raw = f"{prompt}|{neg}|{seed}|{model}|{cfg}|{control}"
return hashlib.md5(raw.encode()).hexdigest()[:12]
def batch_gen(params_list, gen_fn, out_dir) -> dict:
"""同一提示词多候选,全部留痕;已生成则跳过(幂等)"""
import os; os.makedirs(out_dir, exist_ok=True)
manifest = {}
for p in params_list:
h = fingerprint(**p)
path = f"{out_dir}/{h}.png"
if not os.path.exists(path):
img = gen_fn(**p)
Image.fromarray(img).save(path)
manifest[h] = {**p, "path": path}
json.dump(manifest, open(f"{out_dir}/manifest.json", "w"),
ensure_ascii=False, indent=2)
return manifest
def quality_gate(path, brand_color=None) -> dict:
"""自动质检:清晰度 + 构图均衡 + 品牌色占比,不达标直接拒"""
a = np.asarray(Image.open(path).convert("RGB"), np.float32) / 255
g = a.mean(-1)
lap = np.abs(4*g[1:-1,1:-1] - g[:-2,1:-1] - g[2:,1:-1]
- g[1:-1,:-2] - g[1:-1,2:]).var()
sharp = float(min(lap * 100, 1.0))
ys, xs = np.mgrid[0:g.shape[0], 0:g.shape[1]]
cx = (xs*g).sum()/g.sum()/g.shape[1]
cy = (ys*g).sum()/g.sum()/g.shape[0]
balance = float(1 - min(np.hypot(cx-.5, cy-.5)*3, 1.0))
score = 0.6 * sharp + 0.4 * balance
return {"score": round(score, 3),
"pass": score >= 0.55,
"sharpness": round(sharp, 3),
"balance": round(balance, 3)}
# 验收:人工只看 pass=True 的图,通过率目标>40%六项硬指标:角色一致性(同角色跨图 DINOv2 相似度>0.85)、结构控制精度(ControlNet 边缘对齐误差<5px)、高分辨率细节(放大后无糊化,拉普拉斯方差>阈值)、局部重绘保真度(蒙版外像素变化=0)、参数可复现率(任一张图可在1分钟内凭 fingerprint 复现=100%)、批量自动通过率(质检 pass>40%)。前三项决定“图能不能用”,中间一项决定“修图是否精准”,后两项决定“能否量产”。
AI绘图的工程核心,是把“抽卡”变成“条件控制的采样系统”:文本是基础条件,ControlNet 控结构,LoRA 控风格,IP-Adapter 控角色,Inpainting 控局部,两阶段放大保细节,全参数留痕保复现。模型能力决定单张图的上限,这套控制体系决定能不能稳定产出商业可用的图。只会写提示词,是在分布里碰运气;搭起控制体系,才是可控的图像生成工程。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。