Stable Diffusion反向提示词详解:原理、代码实现与应用示例
创作时间:
作者:
@小白创作中心
Stable Diffusion反向提示词详解:原理、代码实现与应用示例
引用
CSDN
1.
https://blog.csdn.net/2301_80239908/article/details/143994420
在之前的文章中,我们先后介绍了Stable Diffusion中的所有关键组件,以及如何根据文本提示词来生成图像的整体流程。在这篇文章中,我将展示如何编辑反向提示词(Negative Prompt)来控制图像生成功能,希望可以为大家提供足够的动力来进行相关研究。
闲话少说,我们直接开始吧!
反向文本提示词概念
反向提示词是我们可以添加到SD模型中的一种额外功能,用于告诉稳定扩散模型我们不想在生成的图像中看到什么。这个功能很流行,可以删除用户不想从原始生成的图像中看到的任何内容。示例图像如下:
原理理解
让我们从导入所需的库和辅助函数开始。所有这些已经在本系列前面的几个组件部分中使用和解释过了,这里就不再累述,我们直接从函数prompt_2_img 开始讲起。 现在,我们将通过传递一个额外的参数neg_prompts来更改prompt_2_img函数。反向文本提示的工作方式是在进行采样时使用用户指定的文本来替代之前空字符串进行条件嵌入(uncond)。原理如下:
代码实现
基于上述分析,我们使用以下代码来实现反向文本提示信息的嵌入,代码如下:
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]
得到结果如下:
非常整洁!我希望这能引起大家一些关于如何使用文本提示词来控制稳定扩散模型输出的想法。
总结
本文重点介绍了使用反向文本提示词来进行条件嵌入实现控制文本生成图像内容的相关背景知识和具体代码实现,并给出了相应的示例。
热门推荐
赵丽颖10月双片上映:从寻子母亲到都市精英的演技蜕变
赵丽颖凭《花千骨》突破转型,用演技征服观众质疑
赵丽颖:从农村女孩到实力派,揭秘演艺圈生存法则
南宁最美打卡地:青秀山黄花风铃木
南宁必游三大景点:青秀山、南湖公园、三街两巷全攻略
寒冬腊月“丰”景正好——四川冬季蔬菜产业发展见闻
红河州:经济挑大梁 创新走在前
云南河口旅游攻略:必去景点与入冬看雪景秘籍
河口区义和镇:厚植文化底蕴 赋能乡村振兴
兰州西固区河口镇:数字赋能 绘就乡村新画卷
一文详解天然气管道安装:国家标准与材料选用要点
工商业用气安全规范:四项强制规定保障用气安全
家庭燃气管道安装指南:7大要点确保用气安全
Qt6.8.0静态编译实战:跨平台开发效率提升指南
Qt6.7.3静态编译最佳实践:从环境搭建到openssl集成
Qt静态编译:提升可移植性和稳定性的关键技能
冷读术:如何通过巧妙话术,深入了解他人信息,精准识人读心技巧
如何在火车动车高铁车上补票并取得报销凭证?
火车补票详细流程:轻松补票,顺利抵达目的地
内地女子乘港铁头等车厢未付款,因初犯免罚1000元
高铁补票怎么补?告别高铁补票烦恼,看完这篇你就懂了!
巡回检察组取景地在哪里 巡回检察组取景地介绍
《巡回检察组》取景地青岛:红瓦绿树、碧海蓝天的美丽画卷
硇洲灯塔:世界仅存两座水晶磨镜灯塔之一
厦门五通灯塔公园:环境优美,自带浪漫,一处被遗忘的小众公园
《与凤行》播放破10亿却口碑两极,赵丽颖演技获赞配音遭吐槽
从茶水丫鬟到视后:赵丽颖的演艺逆袭之路
陕西5个低调小城:人少景美,值得一探究竟
中国传统美食的人文故事
山西古建筑:岁月沉淀的华夏瑰宝,为何能独存千年?