ControlNet是可以在各种输入上进行训练的适配器,如Canny边缘检测、姿态估计或深度估计。ControlNet可以插入管道中,为模型提供额外的调节和控制,以实现更准确的生成。
可以在lllyasviel的存储库中找到在其他输入上训练的其他ControlNet模型。
加载在Canny边缘图像上训练的ControlNet模型,并将其传递给[ControlNetModel]。然后,可以将LCM模型加载到[StableDiffusionControlNetPipeline]中,并用[LCM scheduler]替换调度器。下面尝试将Canny边缘图像传递到管道并生成图像。
# 以下代码为程序运行进行设置
import os os.environ["HF_ENDPOINT"] = "https://hf-mirror.com" mport torch import cv2 import numpy as np from PIL import Image from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, LCMScheduler
from diffusers.utils import load_image, make_image_grid
# 以下代码引入图像处理环节,并进行边缘检测
image = load_image(
"https://hf-mirror.com/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
).resize((512, 512))
image = np.array(image)
low_threshold = 100
high_threshold = 200
image = cv2.Canny(image, low_threshold, high_threshold)
image = image[:, :, None]
image = np.concatenate([image, image, image], axis=2)
canny_image = Image.fromarray(image)
# 以下代码会引入与ControlNet相关的模型
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
pipe = StableDiffusionControlNetPipeline.from_pretrained(
"SimianLuo/LCM_Dreamshaper_v7",
controlnet=controlnet,
torch_dtype=torch.float16,
safety_checker=None,
).to("cuda")
# 以下代码加载LCMScheduler
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
# 以下代码由提示词及边缘检测图片生成图片
generator = torch.manual_seed(0)
image = pipe(
"the mona lisa",
image=canny_image,
num_inference_steps=4,
generator=generator,
).images[0]
image2 = make_image_grid([canny_image, image], rows=1, cols=2)
image2.show()
以下为原始图片
以下为边缘检测结果及生成的图片