Diffusersで高解像度の画像を生成する

ここ1~2ヶ月、DiffusersとModalを使って画像生成の方法を模索していました。知見がたまり、ある程度自由に画像生成できるようになったと思います。せっかくなので、コーディングでつまった箇所や工夫した点をブログにまとめることにしました。この記事では、Diffusersで高解像度の画像を生成する方法について整理します。

背景

Stable Diffusion 1.5、または2系では、生成画像のサイズは標準で512x512、せいぜい1024程度まで。それ以上の解像度の画像を作ろうとすると、人物や背景が崩れてしまいます。1920pや4kの自然な画像を作るには工夫が必要となります。例えば、下記のような方法を私は試しました。

  • Upscalerを使う
    • diffusersのupscaler
    • サードパーティ性のupscaler「Real-ESRGAN」
  • ControlNet 1.1 Tileを使う

最終的にはControlNet 1.1 Tileとupscalerを組み合わせる方法に落ち着きました。

Upscalerを使う

diffusers が提供している upscaler を利用する

diffusersではいくつかのupscalerを利用することができます。

Latent Upscaler(x2)

Stable Diffusion Latent Upscalerと呼ばれる、出力画像の解像度を2倍に高める機能が提供されています。

ベース画像を生成または用意し、Latent Upscalerのパイプラインに渡して推論を実行することで、2倍の解像度の画像が得られます。

upscaler = StableDiffusionLatentUpscalePipeline.from_pretrained(model_id, torch_dtype=torch.float16)
upscaler.to("cuda")

upscaled_image = upscaler(
    prompt=prompt,
    image=base_image, " ←ここにベース画像を渡す
    num_inference_steps=20,
    guidance_scale=0,
    generator=generator,
).images[0]

Super-Resolution(x4)

Super-Resolutionは、出力画像の解像度を4倍にする機能です。使い方はLatent upscalerとほぼ同じです。

サードパーティ製のアップスケーラー「Real-ESRGAN」を利用する

Real-ESRGANは高解像度の画像を出力するためのアプリケーションです。 利用するにはいくつかの依存ライブラリとReal-ESRGAN本体のコードを実行環境に導入する必要があります。

↓必要なライブラリ。pip installで導入。

realesrgan==0.3.0
basicsr>=1.4.2
facexlib>=0.3.0
gfpgan>=1.3.8

下記をwgetやなんらかの手段でダウンロード。

https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth
https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth
https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth
https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth
https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth

Modalではdockerを使うので、Dockerfileとrequirements.txtを用意し、デプロイ時にビルドします。

UpscalerとControlNet 1.1 Tileを組み合わせる

荒い画像を元にアップスケールする場合、顔の崩れや背景の荒い箇所がそのまま拡大されてしまいます。 それを修正する方法の一つとして、img2img 機能を使うやり方があります。一度アップスケールした画像と共に、同じプロンプトと seed を diffusers に渡して再度推論を行うことで、荒い箇所を整えることが可能です。

stable-diffusion-webui では hires.fix と呼ばれる機能で実装されていますが、2023/07/15 時点、diffusers ではまだ機能として提供されていないようでした。そのため、自力で実装しました。

試行錯誤の結果、下記手順の処理でGPUの使用率を抑えつつ、納得いく仕上がりの画像を生成することができました。

  1. txt2imgでベース画像を生成
  2. ベース画像を2~4倍に拡大(Upscalerによるアップスケールではなく、単純な画像のサイズ変更)
  3. 2の画像をControlNet Tileでimg2img推論
  4. 3の画像をUpscalerで高解像度化

下記は実装したコードの一部。全体はGitHubのコードを参照のこと。

 1def run_inference(
 2    self,
 3    prompt: str,
 4    n_prompt: str,
 5    height: int = 512,
 6    width: int = 512,
 7    samples: int = 1,
 8    batch_size: int = 1,
 9    steps: int = 30,
10    seed: int = 1,
11    upscaler: str = "",
12    use_face_enhancer: bool = False,
13    fix_by_controlnet_tile: bool = False,
14) -> list[bytes]:
15
16    """
17    1. ベース画像の生成
18    """
19    max_embeddings_multiples = self._count_token(p=prompt, n=n_prompt)
20    generator = torch.Generator("cuda").manual_seed(seed)
21    with torch.inference_mode():
22        with torch.autocast("cuda"):
23            generated_images = self.pipe.text2img(
24                prompt * batch_size,
25                negative_prompt=n_prompt * batch_size,
26                height=height,
27                width=width,
28                num_inference_steps=steps,
29                guidance_scale=7.5,
30                max_embeddings_multiples=max_embeddings_multiples,
31                generator=generator,
32            ).images
33
34    base_images = generated_images
35
36    """
37    2と3. ベース画像のサイズ拡大とControlNet Tileによる整形
38    """
39    if fix_by_controlnet_tile:
40        for image in base_images:
41            image = self._resize_image(image=image, scale_factor=2)
42            with torch.inference_mode():
43                with torch.autocast("cuda"):
44                    fixed_by_controlnet = self.controlnet_pipe(
45                        prompt=prompt * batch_size,
46                        negative_prompt=n_prompt * batch_size,
47                        num_inference_steps=steps,
48                        strength=0.3,
49                        guidance_scale=7.5,
50                        max_embeddings_multiples=max_embeddings_multiples,
51                        generator=generator,
52                        image=image,
53                    ).images
54        generated_images.extend(fixed_by_controlnet)
55        base_images = fixed_by_controlnet
56
57    """
58    4. Upscalerによるアップスケール
59    """
60    if upscaler != "":
61        upscaled = self._upscale(
62            base_images=base_images,
63            half_precision=False,
64            tile=700,
65            upscaler=upscaler,
66            use_face_enhancer=use_face_enhancer,
67        )
68        generated_images.extend(upscaled)
69
70    image_output = []
71    for image in generated_images:
72        with io.BytesIO() as buf:
73            image.save(buf, format="PNG")
74            image_output.append(buf.getvalue())
75
76    return image_output

まとめ

下図のような画像が得られるようになりました。

お題「暮れかかる湖に佇む黒髪の女性」

↓ベース画像 暮れかかる湖に佇む黒髪の女性(ベース画像)

↓高解像度化 暮れかかる湖に佇む黒髪の女性(高解像度化)