Stable Diffusion反向提示词详解:原理、代码实现与应用示例
创作时间:
作者:
@小白创作中心
Stable Diffusion反向提示词详解:原理、代码实现与应用示例
引用
CSDN
1.
https://m.blog.csdn.net/2301_80239908/article/details/143994420
Stable Diffusion作为当前最流行的AI绘画工具之一,其强大的文本到图像生成能力吸引了众多用户的关注。然而,除了使用正向提示词来引导图像生成外,我们还可以通过反向提示词来控制图像中不希望出现的内容。本文将详细介绍Stable Diffusion中反向提示词的功能、原理和具体实现方法,帮助读者更好地掌握这一实用技巧。
反向文本提示词概念
反向提示词是Stable Diffusion模型中的一种额外功能,用于告诉模型我们不想在生成的图像中看到什么。这个功能非常流行,可以删除用户不想从原始生成的图像中看到的任何内容。示例如下:
原理理解
反向文本提示的工作方式是在进行采样时使用用户指定的文本来替代之前空字符串进行条件嵌入(uncond)。具体来说,我们通过传递一个额外的参数neg_prompts来更改prompt_2_img函数。原理如下:
代码实现
基于上述分析,我们可以使用以下代码来实现反向文本提示信息的嵌入:
def prompt_2_img(prompts, neg_prompts=None, g=7.5, seed=100, steps=70, dim=512, save_int=False):
# Defining batch size
bs = len(prompts)
# Converting textual prompts to embedding
text = text_enc(prompts)
# Adding an unconditional prompt , helps in the generation process
if not neg_prompts:
uncond = text_enc([""] * bs, text.shape[1])
else:
uncond = text_enc(neg_prompts, text.shape[1])
emb = torch.cat([uncond, text])
# Setting the seed
if seed:
torch.manual_seed(seed)
# Initiating random noise
latents = torch.randn((bs, unet.in_channels, dim//8, dim//8))
# Setting number of steps in scheduler
scheduler.set_timesteps(steps)
# Adding noise to the latents
latents = latents.to("cuda").half() * scheduler.init_noise_sigma
# Iterating through defined steps
for i, ts in enumerate(tqdm(scheduler.timesteps)):
# We need to scale the i/p latents to match the variance
inp = scheduler.scale_model_input(torch.cat([latents] * 2), ts)
# Predicting noise residual using U-Net
with torch.no_grad():
u, t = unet(inp, ts, encoder_hidden_states=emb).sample.chunk(2)
# Performing Guidance
pred = u + g*(t-u)
# Conditioning the latents
latents = scheduler.step(pred, ts, latents).prev_sample
# Saving intermediate images
if save_int:
if not os.path.exists(f'./steps'):
os.mkdir(f'./steps')
latents_to_pil(latents)[0].save(f'steps/{i:04}.jpeg')
# Returning the latent representation to output an image of 3x512x512
return latents_to_pil(latents)
整体代码逻辑和之前的逻辑保持一致,唯一不同的就是对反向提示词的处理,已在上一节进行阐述。
功能验证
接着,我们使用以下代码来验证上述函数的功能:
## Image without neg prompt
images = [None, None]
images[0] = prompt_2_img(prompts = ["A dog wearing a white hat"], neg_prompts=[""], steps=50, save_int=False)[0]
images[1] = prompt_2_img(prompts = ["A dog wearing a white hat"], neg_prompts=["White hat"], steps=50, save_int=False)[0]
## Plotting side by side
fig, axs = plt.subplots(1, 2, figsize=(12, 6))
for c, img in enumerate(images):
axs[c].imshow(img)
if c == 0:
axs[c].set_title(f"A dog wearing a white hat")
else:
axs[c].set_title(f"Neg prompt - white hat")
得到结果如下:
扩展
正如我们所看到的,这是一个非常方便的功能,可以根据大家的喜好对图像进行微调。当然也可以用它来生成一张非常逼真的脸,仅仅需要增加更加详细的文本提示描述。让我们试试:
prompt = ['Close-up photography of the face of a 30 years old man with brown eyes, (by Alyssa Monks:1.1), by Joseph Lorusso, by Lilia Alvarado, beautiful lighting, sharp focus, 8k, high res, (pores:0.1), (sweaty:0.8), Masterpiece, Nikon Z9, Award - winning photograph']
neg_prompt = ['lowres, signs, memes, labels, text, food, text, error, mutant, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry, made by children, caricature, ugly, boring, sketch, lacklustre, repetitive, cropped, (long neck), facebook, youtube,body horror, out of frame, mutilated, tiled, frame, border, porcelain skin, doll like, doll']
images = prompt_2_img(prompts = prompt, neg_prompts=neg_prompt, steps=50, save_int=False)
out = images[0]
得到结果如下:
非常整洁!希望这能引起大家一些关于如何使用文本提示词来控制稳定扩散模型输出的想法。
总结
本文重点介绍了使用反向文本提示词来进行条件嵌入实现控制文本生成图像内容的相关背景知识和具体代码实现,并给出了相应的示例。
热门推荐
车祸被起诉,美国法律如何应对?
朱元璋与小明王韩林儿:一段被误解的历史真相
你发现「大米饭」变得越来越好吃了吗?研究表明:稻米品质一直在改善提升!
南瓜早餐饼干:营养丰富,美味可口的健康早餐选择
工伤赔偿报告撰写指南:从收集信息到提出索赔
法院怎样调解工伤赔偿纠纷的
建筑后退红线和用地红线的区别和定义是什么?
二十年,李嘉诚的逐利之途:数次投资,次次盆满钵满!
历史上真实的李世民:文武双全的杰出帝王
Win10开机缓慢?十二个方法提高启动速度
独生子女父母退休,养老金分别领3500和8000元,发的补贴一样吗?
歌手周深在走上坡路还是下坡路?他爆红后的发展揭露了真实答案
梦见手机屏幕碎了意味着什么?探索潜在的心理象征
法院调查令怎么申请
钢结构火灾倒塌伤亡预防,别忘了那顶“斗笠”
新手购车完全指南:燃油车、电动车与混动车如何抉择
汽车上的儿童安全座椅适合哪个年龄段的孩子?
脑机接口!探秘脑科学的无限可能
当代女性不结婚的四大原因深度解析
黄山冬季摄影攻略:捕捉冰雪奇景的绝佳时机
以用人单位未缴社保为由寄出被迫解除通知书,为何还会败诉?
打鼾超响?你可能遇到了超3亿人忽视的“睡眠杀手”!
海宁皮革城旅游攻略:从交通到砍价,教你玩转中国皮都
SAT考试数学难度全解析:挑战与应对策略
三国时期24位杰出武将排名:从武力到智谋的全面评估
香醇美味的甜酒酿醪糟制作全攻略
磁盘结构损坏且无法读取怎么办?这几招快速恢复数据!
鼻塞影響睡眠?4個方法改善鼻腔健康,提升睡眠品質
如何把网页上传到web服务器上
芋叶植物冬天怎么养?冬季养护方法和注意事项是什么?