在本文中,我将解释如何使用Stable Diffusion从风景照片在img2img中生成插图。 句子中难以指导的作文可以通过使用img2img来实现,因此请参考它们。
什么是Img2Img(图像到图像翻译)?
通过向AI输入常规书面指令来生成图像的方法称为txt2img(文本到图像翻译)。
另一方面,IMG2IMG通过输入图像+文本来生成图像。
这使得使用预先准备好的照片和图像来指导单独使用文本难以完成的详细构图成为可能。
Stable Diffusion还有一个使用 img2img 生成插图的功能,所以这次我将解释如何在 Python 中使用 img2img 生成插图。
设置Stable Diffusion 2.x
运行以下命令以安装包:
pip install diffusers[torch]==0.9 transformers
pip install --upgrade --pre triton
获取 StableDiffusion 的存储库并安装它。
pip install --upgrade git+https://github.com/huggingface/diffusers.git transformers accelerate scipy
这样就完成了Stable Diffusion2.0的设置。
生成的源代码
从这里开始,我将解释如何实际使用Stable Diffusion来实现 Python 代码以在 img2img 中生成插图。
蟒蛇代码描述
导入库
导入所需的库。
对于img2img,管道方法将更改为“StableDiffusionImg2ImgPipeline”。
此外,需要PIL图像处理库来读取指令图像。
from diffusers import EulerDiscreteScheduler, StableDiffusionImg2ImgPipeline
from PIL import Image
指定经过训练的模型
指定要与Stable Diffusion一起使用的已训练模型。
这一次,为了输出类似动漫的插图,指定了“andite/anything-v4.0”。 如果要使用常规的Stable Diffusion标准模型,请将其更改为“Stable ai/Stable Diffusion-2”。
model_id = "andite/anything-v4.0"
加载图像
加载指示插图构图的图像并调整其大小。 输出与此指令图像大小相同的图像。 (打开方法参数必须是图像的路径。
#
init_image = Image.open("/content/base-img/fall-3186876_1920.jpg")
init_image = init_image.convert("RGB")
init_image = init_image.resize((768, 768))
管道参数
执行推理过程以生成插图。 将指令图像设置为第二个参数。
在text2img中,图像大小是在管道方法中指定的,但在img2img的情况下,生成的图像的大小由指示图像的大小决定,因此不能在管道方法参数中指定大小。
image = pipe(prompt, image=init_image).images[0]
完整源代码
整个源代码如下。
from datetime import datetime
from diffusers import EulerDiscreteScheduler, StableDiffusionImg2ImgPipeline
import torch
from PIL import Image
#
model_id = "andite/anything-v4.0"
#StableDiffusion
scheduler = EulerDiscreteScheduler.from_pretrained(model_id, subfolder="scheduler")
pipe = StableDiffusionImg2ImgPipeline.from_pretrained(model_id, scheduler=scheduler, torch_dtype=torch.float16)
#
pipe = pipe.to("cuda")
#
init_image = Image.open("(img2img)")
init_image = init_image.convert("RGB")
init_image = init_image.resize((768, 512))
#
prompt = "A girl standing in beautiful nature."
#
num_images = 3
#
for i in range(num_images):
#
image = pipe(prompt, image=init_image).images[0]
#生
date = datetime.now().strftime("%Y%m%d_%H%M%S")
path = date + ".png"
image.save(path)
执行结果
让我们运行上面的 Python 代码来生成一个插图。
这次的目的是查看图像中的说明是否反映在插图中,因此提示只是“站在美丽的大自然中的女孩”。 英文翻译如下。
A girl standing in beautiful nature.
此外,我们还准备了免费材料网站的风景照片,用于说明的图像。
说明图像 1
第一张图片在这里。
指令图像

这是一张森林中道路的照片,上面有美丽的秋叶。
生成的图像
当我指定上一个图像并执行 Python 代码时,生成了下图。


如教学图像所示,生成了一个女孩站在森林中沐浴在阳光下的插图。
说明图像 2
第二张图片在这里。
指令图像

这是一张被绿色植物包围的小木屋的照片。
生成的图像
这一次,我将指令图像的大小调整为768×512的矩形。
当我执行 Python 代码时,生成了下图。

