ジャコ Lab

プログラミング関連のメモ帳的ブログです

ControlNet の Depth を使ってみる

huggingface.co

ControlNet を使ってみる回も5回目。今回は Depth です。

Depth

Depth 画像とは、物体や表面の深さを表している画像とのことです。

transformers をインストール

Depth 画像を抽出するのに transformers モジュールを使うようです。もしかしたらデフォルトで入っているかもしれませんがインストールしておきます

!pip install -U transformers

あとは numpy や Pillow も使いますが、Google Colab では、たぶんデフォルトでインストールされているはずです

投入画像の準備

from diffusers.utils import load_image
import numpy as np
from PIL import Image
from transformers import pipeline as transformersPipeline

# 投入画像の準備
init_image_url = "https://huggingface.co/lllyasviel/control_v11p_sd15_depth/resolve/main/images/input.png"
init_image = load_image(init_image_url)

# コントロールイメージを作成するメソッド
def make_depth_condition(image):
    depth_estimator = transformersPipeline('depth-estimation')
    image = depth_estimator(image)['depth']
    image = np.array(image)
    image = image[:, :, None]
    image = np.concatenate([image, image, image], axis=2)
    return Image.fromarray(image)

control_image = make_depth_condition(init_image)

投入画像 から Depth 画像 を抽出します。
例によって make_depth_condition() メソッドを用意しました。
(中身はコピペなので transformers と numpy で頑張っていることしかわからないです)

(左) 投入画像 | (右) Depth を抽出した画像

ControlNet, Pipeline の準備

import torch
from diffusers import ControlNetModel, StableDiffusionControlNetPipeline, UniPCMultistepScheduler

# ControlNet の準備
controlnet = ControlNetModel.from_pretrained(
    # "lllyasviel/control_v11p_sd15_depth"
    "lllyasviel/control_v11f1p_sd15_depth",
    torch_dtype=torch.float16
)
# Pipeline の準備
pipe = StableDiffusionControlNetPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5", 
    torch_dtype=torch.float16,
    controlnet=controlnet
).to("cuda")
pipe.enable_model_cpu_offload()

# スケジューラーの設定
pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
https://huggingface.co/lllyasviel/control_v11f1p_sd15_depthのサンプルコードを実行したら以下のエラーになりました。

OSError                                   
Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/diffusers/configuration_utils.py in load_config(cls, pretrained_model_name_or_path, return_unused_kwargs, return_commit_hash, **kwargs)
    400                 )
    401             except EntryNotFoundError:
--> 402                 raise EnvironmentError(
    403                     f"{pretrained_model_name_or_path} does not appear to have a file named {cls.config_name}."
    404                 )

OSError: lllyasviel/control_v11p_sd15_depth does not appear to have a file named config.json.
ControlNet の Model は"lllyasviel/control_v11f1p_sd15_depth"が正しい名前のようです

パイプライン実行

prompt = "Stormtrooper's lecture in beautiful lecture hall"
image = pipe(
    prompt,
    num_inference_steps=30,
    generator=torch.Generator(device="cuda").manual_seed(0),
    image=control_image
).images[0]
image

ControlNet の Depth で生成した画像

おまけ

まとめ

深度画像により?奥行きのある立体的な画像が生成されました