Skip to content

外推

外推可以将图像扩展到其原始边界之外,允许你在保留原始图像的同时添加、替换或修改图像中的视觉元素。就像内推一样,你希望用新的视觉元素填充白色区域(在本例中,是原始图像之外的区域),同时保留原始图像(由黑色像素的蒙版表示)。有几种方法可以进行外推,例如使用ControlNet差分扩散

本指南将向你展示如何使用内推模型、ControlNet 和 ZoeDepth 估计器进行外推。

在开始之前,请确保你已安装controlnet_aux 库,以便你可以使用 ZoeDepth 估计器。

py
!pip install -q controlnet_aux

图片准备

首先选择一张要进行外推的图片,并使用像 BRIA-RMBG-1.4 这样的空间来去除背景。

例如,从这双鞋子的图片中去除背景。

original image
background removed

Stable Diffusion XL (SDXL) 模型最适合 1024x1024 像素的图片,但只要你的硬件有足够的内存,你可以将图片调整到任何大小。图片中的透明背景也应该被替换成白色背景。创建一个函数(如下所示)来缩放图片并将其粘贴到白色背景上。

py
import random

import requests
import torch
from controlnet_aux import ZoeDetector
from PIL import Image, ImageOps

from diffusers import (
    AutoencoderKL,
    ControlNetModel,
    StableDiffusionXLControlNetPipeline,
    StableDiffusionXLInpaintPipeline,
)

def scale_and_paste(original_image):
    aspect_ratio = original_image.width / original_image.height

    if original_image.width > original_image.height:
        new_width = 1024
        new_height = round(new_width / aspect_ratio)
    else:
        new_height = 1024
        new_width = round(new_height * aspect_ratio)

    resized_original = original_image.resize((new_width, new_height), Image.LANCZOS)
    white_background = Image.new("RGBA", (1024, 1024), "white")
    x = (1024 - new_width) // 2
    y = (1024 - new_height) // 2
    white_background.paste(resized_original, (x, y), resized_original)

    return resized_original, white_background

original_image = Image.open(
    requests.get(
        "https://huggingface.co/datasets/stevhliu/testing-images/resolve/main/no-background-jordan.png",
        stream=True,
    ).raw
).convert("RGBA")
resized_img, white_bg_image = scale_and_paste(original_image)

为了避免添加不必要的额外细节,使用 ZoeDepth 估计器在生成过程中提供额外的指导,并确保鞋子与原始图片保持一致。

py
zoe = ZoeDetector.from_pretrained("lllyasviel/Annotators")
image_zoe = zoe(white_bg_image, detect_resolution=512, image_resolution=1024)
image_zoe

外扩绘画

图像准备好后,你可以使用 controlnet-inpaint-dreamer-sdxl 在鞋子周围的空白区域生成内容,这是一个针对外扩绘画训练的 SDXL ControlNet 模型。

加载外扩绘画 ControlNet、ZoeDepth 模型、VAE 并将它们传递给 [StableDiffusionXLControlNetPipeline]。然后,你可以创建一个可选的 generate_image 函数(为了方便)来外扩初始图像。

py
controlnets = [
    ControlNetModel.from_pretrained(
        "destitech/controlnet-inpaint-dreamer-sdxl", torch_dtype=torch.float16, variant="fp16"
    ),
    ControlNetModel.from_pretrained(
        "diffusers/controlnet-zoe-depth-sdxl-1.0", torch_dtype=torch.float16
    ),
]
vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16).to("cuda")
pipeline = StableDiffusionXLControlNetPipeline.from_pretrained(
    "SG161222/RealVisXL_V4.0", torch_dtype=torch.float16, variant="fp16", controlnet=controlnets, vae=vae
).to("cuda")

def generate_image(prompt, negative_prompt, inpaint_image, zoe_image, seed: int = None):
    if seed is None:
        seed = random.randint(0, 2**32 - 1)

    generator = torch.Generator(device="cpu").manual_seed(seed)

    image = pipeline(
        prompt,
        negative_prompt=negative_prompt,
        image=[inpaint_image, zoe_image],
        guidance_scale=6.5,
        num_inference_steps=25,
        generator=generator,
        controlnet_conditioning_scale=[0.5, 0.8],
        control_guidance_end=[0.9, 0.6],
    ).images[0]

    return image

prompt = "nike air jordans on a basketball court"
negative_prompt = ""

temp_image = generate_image(prompt, negative_prompt, white_bg_image, image_zoe, 908097)

将原始图像粘贴到初始外扩图像上。你将在后面的步骤中改进外扩的背景。

py
x = (1024 - resized_img.width) // 2
y = (1024 - resized_img.height) // 2
temp_image.paste(resized_img, (x, y), resized_img)
temp_image

TIP

现在是释放一些内存的好时机,如果你内存不足的话!

py
> pipeline=None
> torch.cuda.empty_cache()
> ```

现在你已经有了初始的外扩图像,加载 [`StableDiffusionXLInpaintPipeline`] 和 [RealVisXL](https://hf.co/SG161222/RealVisXL_V4.0) 模型来生成最终的外扩图像,以获得更好的质量。

```py
pipeline = StableDiffusionXLInpaintPipeline.from_pretrained(
    "OzzyGT/RealVisXL_V4.0_inpainting",
    torch_dtype=torch.float16,
    variant="fp16",
    vae=vae,
).to("cuda")

为最终的外部绘制图像准备一个蒙版。为了在原始图像和外部绘制的背景之间创建更自然的过渡,模糊蒙版以帮助它更好地融合。

py
mask = Image.new("L", temp_image.size)
mask.paste(resized_img.split()[3], (x, y))
mask = ImageOps.invert(mask)
final_mask = mask.point(lambda p: p > 128 and 255)
mask_blurred = pipeline.mask_processor.blur(final_mask, blur_factor=20)
mask_blurred

创建一个更好的提示并将其传递给 generate_outpaint 函数以生成最终的外部绘制图像。再次,将原始图像粘贴到最终的外部绘制背景上。

py
def generate_outpaint(prompt, negative_prompt, image, mask, seed: int = None):
    if seed is None:
        seed = random.randint(0, 2**32 - 1)

    generator = torch.Generator(device="cpu").manual_seed(seed)

    image = pipeline(
        prompt,
        negative_prompt=negative_prompt,
        image=image,
        mask_image=mask,
        guidance_scale=10.0,
        strength=0.8,
        num_inference_steps=30,
        generator=generator,
    ).images[0]

    return image

prompt = "high quality photo of nike air jordans on a basketball court, highly detailed"
negative_prompt = ""

final_image = generate_outpaint(prompt, negative_prompt, temp_image, mask_blurred, 7688778)
x = (1024 - resized_img.width) // 2
y = (1024 - resized_img.height) // 2
final_image.paste(resized_img, (x, y), resized_img)
final_image