# Marigold コンピュータービジョン

![marigold](https://marigoldmonodepth.github.io/images/teaser_collage_compressed.jpg)

Marigold は、[Bingxin Ke](http://www.kebingxin.com/)、[Anton Obukhov](https://www.obukhov.ai/)、[Shengyu Huang](https://shengyuh.github.io/)、[Nando Metzger](https://nandometzger.github.io/)、[Rodrigo Caye Daudt](https://rcdaudt.github.io/)、および [Konrad Schindler](https://scholar.google.com/citations?user=FZuNgqIAAAAJ&hl=en) による CVPR 2024 Oral 論文 [Repurposing Diffusion-Based Image Generators for Monocular Depth Estimation](https://huggingface.co/papers/2312.02145) で提案されました。その核心となるアイデアは、**Text-to-Image Latent Diffusion Models (LDMs) の生成事前分布を、従来のコンピュータビジョンタスクに転用すること**です。このアプローチは、上記のティザーで示されているように、**Monocular Depth Estimation** のために Stable Diffusion をファインチューニングすることで検証されました。

Marigoldは、[Bingxin Ke](http://www.kebingxin.com/)、[Kevin Qu](https://www.linkedin.com/in/kevin-qu-b3417621b/?locale=en_US)、[Tianfu Wang](https://tianfwang.github.io/)、[Nando Metzger](https://nandometzger.github.io/)、[Shengyu Huang](https://shengyuh.github.io/)、[Bo Li](https://www.linkedin.com/in/bobboli0202/)、[Anton Obukhov](https://www.obukhov.ai/)、[Konrad Schindler](https://scholar.google.com/citations?user=FZuNgqIAAAAJ&hl=en) による後続論文 [Marigold: Affordable Adaptation of Diffusion-Based Image Generators for Image Analysis](https://huggingface.co/papers/2312.02145) で拡張されました。この研究では、**Surface Normals** や **Intrinsic Image Decomposition** (IID) といった新しいモダリティへの対応が追加され、**Latent Consistency Models** (LCM) 向けのトレーニングプロトコルが導入され、**High-Resolution** (HR) 処理能力が実証されました。

> [!TIP]
> 初期の Marigold モデル（`v1-0` 以前）は、少なくとも 10 ステップの推論で最良の結果を得られるよう最適化されていました。その後、わずか 1〜4 ステップで高品質な推論を可能にする LCM モデルが開発されました。`v1-1` 以降の Marigold モデルは、DDIM スケジューラーを使用することで、わずか 1〜4 ステップで最適な結果を実現します。

## 利用可能なパイプライン

各パイプラインは特定のコンピュータビジョンタスク向けに設計されており、入力されたRGB画像を処理して対応する予測を生成します。現在、以下のコンピュータビジョンタスクが実装されています。

| パイプライン                                                                                                                                          | 推奨モデルチェックポイント                                                                                                                                                                           |                              Spaces（インタラクティブアプリ）                               | 予測されるモダリティ                                                                                                                                                               |
|---------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------:|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [MarigoldDepthPipeline](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py)           | [prs-eth/marigold-depth-v1-1](https://huggingface.co/prs-eth/marigold-depth-v1-1)                                                                                                                       |          [深度推定](https://huggingface.co/spaces/prs-eth/marigold)          | [深度](https://en.wikipedia.org/wiki/Depth_map)、[視差](https://en.wikipedia.org/wiki/Binocular_disparity)                                                                   |
| [MarigoldNormalsPipeline](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py)       | [prs-eth/marigold-normals-v1-1](https://huggingface.co/prs-eth/marigold-normals-v1-1)                                                                                                                   | [法線推定](https://huggingface.co/spaces/prs-eth/marigold-normals) | [表面法線](https://en.wikipedia.org/wiki/Normal_mapping)                                                                                                                    |
| [MarigoldIntrinsicsPipeline](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/marigold/pipeline_marigold_intrinsics.py) | [prs-eth/marigold-iid-appearance-v1-1](https://huggingface.co/prs-eth/marigold-iid-appearance-v1-1)、[prs-eth/marigold-iid-lighting-v1-1](https://huggingface.co/prs-eth/marigold-iid-lighting-v1-1) | [固有画像分解](https://huggingface.co/spaces/prs-eth/marigold-iid)  | [アルベド](https://en.wikipedia.org/wiki/Albedo)、[マテリアル](https://www.n.aiq3d.com/wiki/roughnessmetalnessao-map)、[ライティング](https://en.wikipedia.org/wiki/Diffuse_reflection)   |

## 利用可能なチェックポイント

すべてのオリジナルのチェックポイントは、Hugging Face上の[PRS-ETH](https://huggingface.co/prs-eth/)組織の下で利用可能です。これらは、diffusersのパイプラインおよび[元のコードベース](https://github.com/prs-eth/marigold)での使用を前提として設計されており、新しいモデルのチェックポイントの学習にも利用できます。以下は、推奨されるチェックポイントの概要です。いずれも1ステップから4ステップで信頼性の高い結果を生成します。

| チェックポイント                                                                                          | モダリティ     | コメント                                                                                                                                                                              |
|-----------------------------------------------------------------------------------------------------|--------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [prs-eth/marigold-depth-v1-1](https://huggingface.co/prs-eth/marigold-depth-v1-1)                   | 深さ        | Affine-invariant depth predictionでは、各ピクセルに0（近面）から1（遠面）の値が割り当てられ、両方の面は推論中にモデルによって決定されます。                    |
| [prs-eth/marigold-normals-v0-1](https://huggingface.co/prs-eth/marigold-normals-v0-1)               | ノーマル      | 表面法線の予測値は、スクリーン空間のカメラにおける単位長さの3次元ベクトルであり、値の範囲は-1から1です。                                                        |
| [prs-eth/marigold-iid-appearance-v1-1](https://huggingface.co/prs-eth/marigold-iid-appearance-v1-1) | イントリニクス   | InteriorVerseの分解は、Albedoと2つのBRDFマテリアル特性であるRoughnessとMetallicityで構成されています。                                                                      |
| [prs-eth/marigold-iid-lighting-v1-1](https://huggingface.co/prs-eth/marigold-iid-lighting-v1-1)     | イントリニクス   | HyperSimによる画像 $I$ の分解は、アルベド $A$、ディフューズシェーディング $S$、および非ディフューズ残差 $R$ で構成され、$I = A*S+R$ と表されます。 |

> [!TIP]
> スケジューラーの [ガイド](../../using-diffusers/schedulers) を確認し、スケジューラーの速度と品質のトレードオフをどのように探索するかを学び、[パイプライン間でコンポーネントを再利用する](../../using-diffusers/loading#reusing-models-in-multiple-pipelines) セクションを参照して、同じコンポーネントを複数のパイプラインに効率的にロードする方法を学びましょう。また、このパイプラインのメモリ使用量を削減する方法については、[こちら](./stable_diffusion/svd#reduce-memory-usage) の ["Reduce memory usage"] セクションを参照してください。

> [!WARNING]
> Marigold パイプラインは、スケジューラがモデルチェックポイントに埋め込まれていることを前提として設計・テストされました。最適な推論ステップ数はスケジューラによって異なり、すべてのケースで最も良い結果をもたらす普遍的な値はありません。この点に対応するため、パイプラインの `__call__` メソッドにおける `num_inference_steps` パラメータのデフォルト値は `None` です（API リファレンスを参照）。明示的に設定されない場合、チェックポイントの設定ファイル（`model_index.json`）内の `default_denoising_steps` フィールドの値が継承されます。これにより、`image` 引数のみを指定してパイプラインを呼び出す場合でも、高品質な予測が得られます。

以下の例は主に深度予測について示されていますが、他のサポートされているモダリティにも普遍的に適用できます。Midjourneyで生成したアルベルト・アインシュタインの同じ入力画像を使用して予測結果をデモしています。これにより、さまざまなモダリティとチェックポイント間の予測の可視化を比較しやすくなります。

  
    
    
      すべての Marigold パイプラインの例として使用する入力画像
    
  

## 深度予測

深度予測を取得するには、`prs-eth/marigold-depth-v1-1` チェックポイントを [MarigoldDepthPipeline](/docs/diffusers/main/ja/api/pipelines/marigold#diffusers.MarigoldDepthPipeline) に読み込み、画像をパイプラインに通し、予測結果を保存します。

```python
import diffusers
import torch

pipe = diffusers.MarigoldDepthPipeline.from_pretrained(
    "prs-eth/marigold-depth-v1-1", variant="fp16", dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"

image = diffusers.utils.load_image("https://marigoldmonodepth.github.io/images/einstein.jpg")

depth = pipe(image)

vis = pipe.image_processor.visualize_depth(depth.prediction)
vis[0].save("einstein_depth.png")

depth_16bit = pipe.image_processor.export_depth_to_16bit_png(depth.prediction)
depth_16bit[0].save("einstein_depth_16bit.png")
```

[visualize_depth()](/docs/diffusers/main/ja/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldImageProcessor.visualize_depth) 関数は、[matplotlib のカラーマップ](https://matplotlib.org/stable/users/explain/colors/colormaps.html)（デフォルトは `Spectral`）を適用して、単一チャネルの `[0, 1]` 深度範囲の予測ピクセル値を RGB 画像にマッピングします。`Spectral` カラーマップでは、深度が近いピクセルは赤、遠いピクセルは青で描画されます。16 ビット PNG ファイルには、`[0, 1]` 範囲から `[0, 65535]` 範囲へ線形にマッピングされた単一チャネルの値が保存されます。以下は、生データと可視化された予測結果です。可視化では、暗く手前にある領域（ひげ）がより明確に区別できます。

  
    
    
      予測深度 (16ビット PNG)
    
  
  
    
    
      予測深度の可視化（スペクトル）
    
  

## 法線推定

`prs-eth/marigold-normals-v1-1` チェックポイントを [MarigoldNormalsPipeline](/docs/diffusers/main/ja/api/pipelines/marigold#diffusers.MarigoldNormalsPipeline) に読み込み、画像をパイプラインに通して、予測結果を保存します。

```python
import diffusers
import torch

pipe = diffusers.MarigoldNormalsPipeline.from_pretrained(
    "prs-eth/marigold-normals-v1-1", variant="fp16", dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"

image = diffusers.utils.load_image("https://marigoldmonodepth.github.io/images/einstein.jpg")

normals = pipe(image)

vis = pipe.image_processor.visualize_normals(normals.prediction)
vis[0].save("einstein_normals.png")
```

[visualize_normals()](/docs/diffusers/main/ja/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldImageProcessor.visualize_normals) は、ピクセル値が `[-1, 1]` の範囲にある3次元の予測をRGB画像に変換します。この可視化関数は、座標系の他の選択と互換性を持たせるために、表面法線の軸を反転させることをサポートしています。概念的には、各ピクセルは、`X` 軸が右を向き、`Y` 軸が上を向き、`Z` 軸が視聴者に向いている座標系における表面法線ベクトルに基づいて描画されます。以下は可視化された予測です：

  
    
    
      予測された表面法線の可視化
    
  

この例では、鼻先にはほぼ確実に、表面法線ベクトルが視聴者に向かって真直ぐに伸びる表面の点があり、その座標は`[0, 0, 1]`です。このベクトルはRGBの`[128, 128, 255]`にマッピングされ、これは紫がかった青色に対応します。同様に、画像の右側の頬にある表面法線は大きな`X`成分を持ち、赤みの色調を高めます。肩の上向きに伸びる大きな`Y`成分を持つ点は、緑色を強めます。

## 固有画像分解

Marigold は、Intrinsic Image Decomposition (IID) 用の 2 つのモデル、"Appearance" と "Lighting" を提供しています。各モデルは、それぞれ InteriorVerse と Hypersim のアノテーションから導出された Albedo マップを生成します。

- 「Appearance」モデルは、Materialの特性であるRoughnessとMetallicityも推定します。
- 「Lighting」モデルは、Diffuse Shading と Non-diffuse Residual を生成します。

以下は、"Appearance" モデルによる予測結果を保存するサンプルコードです：

```python
import diffusers
import torch

pipe = diffusers.MarigoldIntrinsicsPipeline.from_pretrained(
    "prs-eth/marigold-iid-appearance-v1-1", variant="fp16", dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"

image = diffusers.utils.load_image("https://marigoldmonodepth.github.io/images/einstein.jpg")

intrinsics = pipe(image)

vis = pipe.image_processor.visualize_intrinsics(intrinsics.prediction, pipe.target_properties)
vis[0]["albedo"].save("einstein_albedo.png")
vis[0]["roughness"].save("einstein_roughness.png")
vis[0]["metallicity"].save("einstein_metallicity.png")
```

"Lighting"モデルによる予測を示す別の例:

```python
import diffusers
import torch

pipe = diffusers.MarigoldIntrinsicsPipeline.from_pretrained(
    "prs-eth/marigold-iid-lighting-v1-1", variant="fp16", dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"

image = diffusers.utils.load_image("https://marigoldmonodepth.github.io/images/einstein.jpg")

intrinsics = pipe(image)

vis = pipe.image_processor.visualize_intrinsics(intrinsics.prediction, pipe.target_properties)
vis[0]["albedo"].save("einstein_albedo.png")
vis[0]["shading"].save("einstein_shading.png")
vis[0]["residual"].save("einstein_residual.png")
```

両方のモデルは同じパイプラインを共有しつつ、異なる分解タイプをサポートしています。正確な分解のパラメータ化（例: sRGB空間と線形空間）は、[visualize_intrinsics()](/docs/diffusers/main/ja/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldImageProcessor.visualize_intrinsics)関数に渡される`pipe.target_properties`辞書に格納されています。

以下は、予測された分解出力を示すいくつかの例です。すべてのモダリティは、[Intrinsic Image Decomposition](https://huggingface.co/spaces/prs-eth/marigold-iid) Space で確認できます。

  
    
    
      予測アルベド（「Appearance」モデル）
    
  
  
    
    
      予測されるディフューズシェーディング（「Lighting」モデル）
    
  

## 推論の高速化

上記のクイックスタートのスニペットは、品質と速度の両面ですでに最適化されており、チェックポイントを読み込み、`fp16`の重みと計算のバリアントを利用し、デノイジング拡散ステップのデフォルト回数（4回）を実行します。予測品質を犠牲にして推論を高速化する最初のステップは、デノイジング拡散ステップを最小限に減らすことです：

```diff
  import diffusers
  import torch

  pipe = diffusers.MarigoldDepthPipeline.from_pretrained(
      "prs-eth/marigold-depth-v1-1", variant="fp16", dtype=torch.float16
  ).to("cuda")  # or "mps", "xpu", "cpu"

  image = diffusers.utils.load_image("https://marigoldmonodepth.github.io/images/einstein.jpg")
  
- depth = pipe(image)
+ depth = pipe(image, num_inference_steps=1)
```

この変更により、`pipe` の呼び出しは RTX 3090 GPU 上で 280ms で完了します。内部では、まず入力画像が Stable Diffusion の VAE エンコーダーによってエンコードされ、次に U-Net によって 1 ステップのデノイジングが実行されます。最後に、予測された潜在変数が VAE デコーダーによってピクセル空間にデコードされます。この構成では、3 つのモジュール呼び出しのうち 2 つが、LDM のピクセル空間と潜在空間の相互変換に費やされています。Marigold の潜在空間は Stable Diffusion 2.0 と互換性があるため、[軽量な SD VAE の代替実装](../models/autoencoder_tiny) を使用することで、推論を 3 倍以上高速化し、RTX 3090 での呼び出し時間を 85ms に短縮できます。なお、軽量な VAE を使用すると、予測の視覚的な品質がわずかに低下する可能性があります。

```diff
  import diffusers
  import torch

  pipe = diffusers.MarigoldDepthPipeline.from_pretrained(
      "prs-eth/marigold-depth-v1-1", variant="fp16", dtype=torch.float16
  ).to("cuda")  # or "mps", "xpu", "cpu"

+ pipe.vae = diffusers.AutoencoderTiny.from_pretrained(
+     "madebyollin/taesd", dtype=torch.float16
+ ).cuda()

  image = diffusers.utils.load_image("https://marigoldmonodepth.github.io/images/einstein.jpg")

  depth = pipe(image, num_inference_steps=1)
```

これまで、拡散ステップ数とモデルコンポーネントを最適化してきました。自己注意（self-attention）操作は計算量の大部分を占めています。より効率的なアテンションプロセッサを使用することで、これらを高速化できます。

```diff
  import diffusers
  import torch
+ from diffusers.models.attention_processor import AttnProcessor2_0

  pipe = diffusers.MarigoldDepthPipeline.from_pretrained(
      "prs-eth/marigold-depth-v1-1", variant="fp16", dtype=torch.float16
  ).to("cuda")  # or "mps", "xpu", "cpu"

+ pipe.vae.set_attn_processor(AttnProcessor2_0()) 
+ pipe.unet.set_attn_processor(AttnProcessor2_0())

  image = diffusers.utils.load_image("https://marigoldmonodepth.github.io/images/einstein.jpg")

  depth = pipe(image, num_inference_steps=1)
```

最後に、[最適化](../../optimization/fp16#torchcompile)で提案されているように、`torch.compile`を有効にすることで、対象ハードウェアに応じてパフォーマンスをさらに向上させることができます。ただし、コンパイルには最初のパイプライン呼び出し時に大きなオーバーヘッドが発生するため、ループ内のように同じパイプラインインスタンスが繰り返し呼び出される場合にのみ有効です。

```diff
  import diffusers
  import torch
  from diffusers.models.attention_processor import AttnProcessor2_0

  pipe = diffusers.MarigoldDepthPipeline.from_pretrained(
      "prs-eth/marigold-depth-v1-1", variant="fp16", dtype=torch.float16
  ).to("cuda")  # or "mps", "xpu", "cpu"

  pipe.vae.set_attn_processor(AttnProcessor2_0()) 
  pipe.unet.set_attn_processor(AttnProcessor2_0())

+ pipe.vae = torch.compile(pipe.vae, mode="reduce-overhead", fullgraph=True)
+ pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)

  image = diffusers.utils.load_image("https://marigoldmonodepth.github.io/images/einstein.jpg")

  depth = pipe(image, num_inference_steps=1)
```

## 精度の最大化とアンサンブル

Marigoldのパイプラインには、異なるランダムな潜在変数からの複数の予測を組み合わせる組み込みのアンサンブル機構があります。これは拡散モデルの生成特性を活かして予測の精度を向上させるための、直接的な手法です。`ensemble_size`引数が`3`以上である場合、アンサンブル処理が自動的に有効になります。最大限の精度を追求する場合は、`num_inference_steps`を`ensemble_size`と同時に調整するのが理にかなっています。推奨値はチェックポイントによって異なりますが、主にスケジューラーの種類に依存します。アンサンブルの効果は、特にサーフェスノーマルにおいて顕著に現れます。

```diff
  import diffusers

  pipe = diffusers.MarigoldNormalsPipeline.from_pretrained("prs-eth/marigold-normals-v1-1").to("cuda")  # or "mps", "xpu", "cpu"

  image = diffusers.utils.load_image("https://marigoldmonodepth.github.io/images/einstein.jpg")

- depth = pipe(image)
+ depth = pipe(image, num_inference_steps=10, ensemble_size=5)

  vis = pipe.image_processor.visualize_normals(depth.prediction)
  vis[0].save("einstein_normals.png")
```

  
    
    
      サーフェスノーマル、アンサンブルなし
    
  
  
    
    
      アンサンブルを用いた表面法線
    
  

ご覧のとおり、髪などの細粒度の構造を持つ領域では、より保守的かつ平均的に正確な予測が得られました。このような結果は、3D再構築など、精度に敏感な下流タスクにより適しています。

## 時間的一整合性を保ちたフレーム単位の動画処理

Marigold は生成モデルであるため、各予測は一意であり、潜在変数の初期化のためにサンプリングされるランダムノイズによって定義されます。これは、次の動画に示されるように、従来のエンドツーエンドの稠密回帰ネットワークと比較して、明らかな欠点となります。

  
    
    入力動画
  
  
    
    入力動画の各フレームに独立してMarigold Depthを適用
  

この問題を解決するために、パイプラインに`latents`引数を渡すことができます。これは拡散の開始点を定義します。経験的に、同じ開始点のノイズ潜在変数と、前フレームの予測に対応する潜在変数の凸結合を用いることで、十分に滑らかな結果が得られることが確認されています。以下のスニペットにその実装を示します。

```python
import imageio
import diffusers
import torch
from diffusers.models.attention_processor import AttnProcessor2_0
from PIL import Image
from tqdm import tqdm

device = "cuda"  # or "mps", "xpu", "cpu"
path_in = "https://huggingface.co/spaces/prs-eth/marigold-lcm/resolve/c7adb5427947d2680944f898cd91d386bf0d4924/files/video/obama.mp4"
path_out = "obama_depth.gif"

pipe = diffusers.MarigoldDepthPipeline.from_pretrained(
    "prs-eth/marigold-depth-v1-1", variant="fp16", dtype=torch.float16
).to(device)
pipe.vae = diffusers.AutoencoderTiny.from_pretrained(
    "madebyollin/taesd", dtype=torch.float16
).to(device)
pipe.unet.set_attn_processor(AttnProcessor2_0())
pipe.vae = torch.compile(pipe.vae, mode="reduce-overhead", fullgraph=True)
pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
pipe.set_progress_bar_config(disable=True)

with imageio.get_reader(path_in) as reader:
    size = reader.get_meta_data()['size']
    last_frame_latent = None
    latent_common = torch.randn(
        (1, 4, 768 * size[1] // (8 * max(size)), 768 * size[0] // (8 * max(size)))
    ).to(device=device, dtype=torch.float16)

    out = []
    for frame_id, frame in tqdm(enumerate(reader), desc="Processing Video"):
        frame = Image.fromarray(frame)
        latents = latent_common
        if last_frame_latent is not None:
            latents = 0.9 * latents + 0.1 * last_frame_latent

        depth = pipe(
            frame,
            num_inference_steps=1,
            match_input_resolution=False, 
            latents=latents, 
            output_latent=True,
        )
        last_frame_latent = depth.latent
        out.append(pipe.image_processor.visualize_depth(depth.prediction)[0])

    diffusers.utils.export_to_gif(out, path_out, fps=reader.get_meta_data()['fps'])
```

ここでは、拡散プロセスは与えられた計算済み潜在変数から開始されます。パイプラインは`output_latent=True`を設定して`out.latent`にアクセスし、次のフレームの潜在変数の初期化への寄与を計算します。その結果、はるかに安定した出力が得られるようになりました：

  
    
    入力動画の各フレームに独立してMarigold Depthを適用
  
  
    
    強制された潜在変数初期化を用いた Marigold Depth
  

## ControlNet 用の Marigold

拡散モデルによる深度予測の非常に一般的な応用として、ControlNetとの組み合わせが挙げられます。ControlNetから高品質な結果を得るためには、深度の鮮明さが重要な役割を果たします。上記の他の手法との比較からもわかるように、Marigoldはこのタスクに優れています。以下のスニペットは、画像を読み込み、深度を計算し、互換性のある形式でControlNetに渡す方法を示しています。

```python
import torch
import diffusers

device = "cuda"  # or "mps", "xpu", "cpu"
generator = torch.Generator(device=device).manual_seed(2024)
image = diffusers.utils.load_image(
    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/controlnet_depth_source.png"
)

pipe = diffusers.MarigoldDepthPipeline.from_pretrained(
    "prs-eth/marigold-depth-v1-1", dtype=torch.float16, variant="fp16"
).to(device)

depth_image = pipe(image, generator=generator).prediction
depth_image = pipe.image_processor.visualize_depth(depth_image, color_map="binary")
depth_image[0].save("motorcycle_controlnet_depth.png")

controlnet = diffusers.ControlNetModel.from_pretrained(
    "diffusers/controlnet-depth-sdxl-1.0", dtype=torch.float16, variant="fp16"
).to(device)
pipe = diffusers.StableDiffusionXLControlNetPipeline.from_pretrained(
    "SG161222/RealVisXL_V4.0", dtype=torch.float16, variant="fp16", controlnet=controlnet
).to(device)
pipe.scheduler = diffusers.DPMSolverMultistepScheduler.from_config(pipe.scheduler.config, use_karras_sigmas=True)

controlnet_out = pipe(
    prompt="high quality photo of a sports bike, city",
    negative_prompt="",
    guidance_scale=6.5,
    num_inference_steps=25,
    image=depth_image,
    controlnet_conditioning_scale=0.7,
    control_guidance_end=0.7,
    generator=generator,
).images
controlnet_out[0].save("motorcycle_controlnet_out.png")
```

  
    
    
      入力画像
    
  
  
    
    
      ControlNet と互換性のある形式の深度
    
  
  
    
    
      深度とプロンプト「high quality photo of a sports bike, city」を条件として、ControlNetによる生成
    
  

## 定量的評価

Marigoldを標準的なリーダーボードやベンチマーク（NYU、KITTI、その他のデータセットなど）で定量的に評価するには、論文に示された評価プロトコルに従ってください。フルプレシションのfp32モデルを読み込み、`num_inference_steps`と`ensemble_size`には適切な値を設定します。再現性を確保するために、乱数のシードを任意で設定できます。`batch_size`を最大化することで、デバイスの利用率を最大限に高めることができます。

```python
import diffusers
import torch

device = "cuda"  # or "mps", "xpu", "cpu"
seed = 2024

generator = torch.Generator(device=device).manual_seed(seed)
pipe = diffusers.MarigoldDepthPipeline.from_pretrained("prs-eth/marigold-depth-v1-1").to(device)

image = diffusers.utils.load_image("https://marigoldmonodepth.github.io/images/einstein.jpg")

depth = pipe(
    image, 
    num_inference_steps=4,  # set according to the evaluation protocol from the paper
    ensemble_size=10,       # set according to the evaluation protocol from the paper
    generator=generator,
)

# evaluate metrics
```

## 予測的不確実性の使用

Marigold パイプラインに組み込まれたアンサンブル機構は、異なるランダムな潜在変数から得られた複数の予測を組み合わせます。この副次的な効果として、認識論的不確実性（モデルの不確実性）を定量化するために利用できます。`ensemble_size` を 3 以上に設定し、`output_uncertainty=True` を指定するだけです。得られた不確実性は、出力の `uncertainty` フィールドで利用できます。以下のように可視化できます:

```python
import diffusers
import torch

pipe = diffusers.MarigoldDepthPipeline.from_pretrained(
    "prs-eth/marigold-depth-v1-1", variant="fp16", dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"

image = diffusers.utils.load_image("https://marigoldmonodepth.github.io/images/einstein.jpg")

depth = pipe(
	image,
	ensemble_size=10,  # any number >= 3
	output_uncertainty=True,
)

uncertainty = pipe.image_processor.visualize_uncertainty(depth.uncertainty)
uncertainty[0].save("einstein_depth_uncertainty.png")
```

  
    
    
      深度の不確実性
    
  
  
    
    
      サーフェスノーマルの不確実性
    
  
  
    
    
      アルベドの不確実性
    
  

不確実性の解釈は簡単です。値が高い（白）ほど、モデルが一貫した予測を行うのが難しいピクセルに対応します。
- 深度モデルは、物体の深度が急激に変化する不連続点の周辺で、最も不確実性が高くなります。
- サーフェスノーマルモデルは、髪のような細かな構造や、such as the
首元
- アルベドの不確実性は、各カラーチャネルごとに独立して不確実性を捉えるため、RGB画像として表現されます。
深度や表面法線とは異なり、影の付いた領域や不連続点では、その値が高くなります。

## Marigold Depth Prediction API[[diffusers.MarigoldDepthPipeline]]

#### diffusers.MarigoldDepthPipeline[[diffusers.MarigoldDepthPipeline]]

```python
diffusers.MarigoldDepthPipeline(unet: UNet2DConditionModel, vae: AutoencoderKL, scheduler: diffusers.schedulers.scheduling_ddim.DDIMScheduler | diffusers.schedulers.scheduling_lcm.LCMScheduler, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, prediction_type: str | None = None, scale_invariant: bool | None = True, shift_invariant: bool | None = True, default_denoising_steps: int | None = None, default_processing_resolution: int | None = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py#L104)

**パラメータ:**

unet (`UNet2DConditionModel`) : 画像の潜在変数に条件付けられ、深度の潜在変数のノイズ除去を行う条件付き U-Net。

vae (`AutoencoderKL`) : 画像と予測を潜在表現にエンコードおよびデコードするための Variational Auto-Encoder (VAE) モデル。

scheduler (`DDIMScheduler` または `LCMScheduler`) : `unet` と組み合わせて、エンコードされた画像の潜在変数からノイズを除去するために使用するスケジューラ。

text_encoder (`CLIPTextModel`) : 空のテキスト埋め込み用のテキストエンコーダー。

tokenizer (`CLIPTokenizer`) : CLIP トークナイザー。

prediction_type (`str`, *任意*) : モデルが生成する予測の型。

scale_invariant (`bool`, *任意*) : 予測される深度マップがスケール不変であるかどうかを指定するモデルのプロパティです。この値はモデルの config に設定する必要があります。`shift_invariant=True` フラグと組み合わせて使用する場合、モデルは「アフィン不変」とも呼ばれます。なお、この値の上書きはサポートされていません。

shift_invariant (`bool`, *任意*) : 予測される深度マップがシフト不変であるかどうかを指定するモデルのプロパティです。この値はモデルの設定で設定する必要があります。`scale_invariant=True` フラグと組み合わせて使用する場合、このモデルは「アフィン不変」とも呼ばれます。なお、この値の上書きはサポートされていません。

default_denoising_steps (`int`, *optional*) : 指定されたモデルで、適切な品質の予測を生成するために必要な、デノイジング拡散ステップの最小値です。この値はモデルの config に設定する必要があります。パイプラインを呼び出す際に `num_inference_steps` を明示的に設定しない場合、デフォルト値が使用されます。これは、非常に短いデノイジングスケジュールに依存するもの（`LCMScheduler`）や、完全な拡散スケジュールを持つもの（`DDIMScheduler`）など、このパイプラインと互換性のあるさまざまなモデルのバリエーションで、適切な結果を得ることを保証するために必要です。

default_processing_resolution (`int`、*任意*) : パイプラインの `processing_resolution` パラメータの推奨値です。この値はモデルの config に設定する必要があります。パイプラインを呼び出す際に `processing_resolution` を明示的に設定しない場合、デフォルト値が使用されます。これは、最適な処理解像度の値が異なるように学習されたさまざまなモデルのバリエーションに対して、妥当な結果を得ることを保証するために必要です。

Marigold手法を用いた単眼深度推定のためのPipeline: https://marigoldmonodepth.github.io

このモデルは [DiffusionPipeline](/docs/diffusers/main/ja/api/pipelines/overview#diffusers.DiffusionPipeline) を継承しています。ライブラリがすべてのパイプラインに対して実装している汎用的なメソッド（ダウンロードや保存、特定のデバイスでの実行など）については、スーパークラスのドキュメントを参照してください。

#### __call__[[diffusers.MarigoldDepthPipeline.__call__]]

```python
__call__(image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], num_inference_steps: int | None = None, ensemble_size: int = 1, processing_resolution: int | None = None, match_input_resolution: bool = True, resample_method_input: str = 'bilinear', resample_method_output: str = 'bilinear', batch_size: int = 1, ensembling_kwargs: dict[str, typing.Any] | None = None, latents: typing.Union[torch.Tensor, list[torch.Tensor], NoneType] = None, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, output_type: str = 'np', output_uncertainty: bool = False, output_latent: bool = False, return_dict: bool = True)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py#L347)

**パラメータ:**

image (`PIL.Image.Image`、`np.ndarray`、`torch.Tensor`、`list[PIL.Image.Image]`、`list[np.ndarray]`)、: `list[torch.Tensor]`: 深度推定タスクの入力として使用される入力画像または画像群。配列やテンソルの場合、想定される値の範囲は`[0, 1]`です。4次元の配列またはテンソルを渡すことで、画像のバッチを渡すことができます。また、2次元または3次元の配列またはテンソルの画像のリストを渡すことも可能です。後者の場合、リストのすべての要素は同じ幅と高さを有する必要があります。

num_inference_steps (`int`、*任意*、デフォルトは `None`) : 推論時のデノイジング拡散ステップ数。デフォルト値 `None` の場合、自動的に選択されます。

ensemble_size (`int`、デフォルトは `1`) : アンサンブル予測の数。値を大きくすると、測定可能な改善と視覚的な劣化が確認されます。

processing_resolution (`int`、*任意*、デフォルトは `None`) : 実際の処理解像度。`0` に設定すると、入力画像の大きい方の寸法に一致します。これにより予測がより鮮明になりますが、グローバルなコンテキスト全体が失われる可能性もあります。デフォルト値 `None` は、モデル設定から最適な値に解決されます。

match_input_resolution (`bool`、*任意*、デフォルトは`True`) : 有効な場合、出力予測は入力次元に合わせてリサイズされます。無効な場合、出力の長い辺は`processing_resolution`に等しくなります。

resample_method_input (`str`、*任意*、デフォルトは`"bilinear"`) : 入力画像を`processing_resolution`にリサイズするために使用されるリサンプリング手法です。受け入れられる値は、`"nearest"`、`"nearest-exact"`、`"bilinear"`、`"bicubic"`、または`"area"`です。

resample_method_output (`str`、*任意*、デフォルトは`"bilinear"`) : 出力予測を入力解像度に合わせるためにリサイズする際に使用するリサンプリング手法。受け入れられる値は`"nearest"`、`"nearest-exact"`、`"bilinear"`、`"bicubic"`、または`"area"`です。

batch_size (`int`、*任意*、デフォルトは `1`) : バッチサイズ。`ensemble_size` を設定するか、画像のテンソルを渡す場合にのみ関連します。

ensembling_kwargs (`dict`, *省略可*、デフォルトは `None`) : 精密なアンサンブル制御のための引数を含む追加の辞書。利用可能なオプションは以下の通りです: - reduction (`str`, *省略可*、デフォルトは `"median"`): 各ピクセル位置に適用されるアンサンブル関数を定義します。`"median"` または `"mean"` のいずれかです。 - regularizer_strength (`float`, *省略可*、デフォルトは `0.02`): 0 から 1 までの単位範囲に整列された予測を引っ張る正則化の強さ。 - max_iter (`int`, *省略可*、デフォルトは `2`): 整列ソルバーのステップ数の最大値。`scipy.optimize.minimize` 関数の `options` 引数を参照してください。 - tol (`float`, *省略可*、デフォルトは `1e-3`): 整列ソルバーの許容誤差。許容誤差に達するとソルバーは停止します。 - max_res (`int`, *省略可*、デフォルトは `None`): 整列が行われる解像度。`None` は `processing_resolution` と一致します。

latents (`torch.Tensor`、または `list[torch.Tensor]`、*任意*、デフォルトは `None`) : ランダム初期化に置き換えるための潜在ノイズテンソルです。これらは、直前の関数呼び出しの出力から取得できます。

generator (`torch.Generator`、または `list[torch.Generator]`、*任意*、デフォルトは `None`) : 再現性を確保するための乱数生成器オブジェクト。

output_type (`str`、*任意*、デフォルトは`"np"`) : 出力の`prediction`および任意の`uncertainty`フィールドの推奨フォーマット。受け入れられる値は、`"np"`（numpy配列）または`"pt"`（torchテンソル）です。

output_uncertainty (`bool`、*任意*、デフォルトは`False`) : 有効にすると、`ensemble_size`引数が2より大きい値に設定されている場合、出力の`uncertainty`フィールドに予測不確実性マップが含まれます。

output_latent (`bool`、*任意*、デフォルトは`False`) : 有効にすると、出力の`latent`フィールドには、アンサンブル内の予測に対応する潜在コードが含まれます。これらのコードは保存・変更でき、`latents`引数を用いた後続の呼び出しに使用できます。

return_dict (`bool`、*任意*、デフォルトは`True`) : プレーンなタプルではなく、[MarigoldDepthOutput](/docs/diffusers/main/ja/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldDepthOutput)を返すかどうかを指定します。

**戻り値:** [MarigoldDepthOutput](/docs/diffusers/main/ja/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldDepthOutput) または `tuple`

`return_dict` が `True` の場合、[MarigoldDepthOutput](/docs/diffusers/main/ja/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldDepthOutput) が返され、それ以外の場合は `tuple` が返されます。このとき、最初の要素は予測値、2番目の要素は不確実性（または `None`）、3番目の要素は潜在変数（または `None`）です。

パイプラインを呼び出したときに実行される関数。

例:
```py
>>> import diffusers
>>> import torch

>>> pipe = diffusers.MarigoldDepthPipeline.from_pretrained(
...     "prs-eth/marigold-depth-v1-1", variant="fp16", torch_dtype=torch.float16
... ).to("cuda")

>>> image = diffusers.utils.load_image("https://marigoldmonodepth.github.io/images/einstein.jpg")
>>> depth = pipe(image)

>>> vis = pipe.image_processor.visualize_depth(depth.prediction)
>>> vis[0].save("einstein_depth.png")

>>> depth_16bit = pipe.image_processor.export_depth_to_16bit_png(depth.prediction)
>>> depth_16bit[0].save("einstein_depth_16bit.png")
```

#### diffusers.pipelines.marigold.MarigoldDepthOutput[[diffusers.pipelines.marigold.MarigoldDepthOutput]]

```python
diffusers.pipelines.marigold.MarigoldDepthOutput(prediction: typing.Union[numpy.ndarray, torch.Tensor], uncertainty: typing.Union[NoneType, numpy.ndarray, torch.Tensor], latent: typing.Optional[torch.Tensor])
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py#L83)

**パラメータ:**

prediction (`np.ndarray`、`torch.Tensor`) : 値が [0, 1] の範囲にある予測深度マップ。`torch.Tensor` の場合は形状が `numimages × 1 × height × width`、`np.ndarray` の場合は `numimages × height × width × 1` です。

uncertainty (`None`, `np.ndarray`, `torch.Tensor`) : アンサンブルから計算された不確実性マップ。値は [0, 1] の範囲です。`torch.Tensor` の場合、形状は `numimages × 1 × height × width` であり、`np.ndarray` の場合は `numimages × height × width × 1` です。

latent (`None`, `torch.Tensor`) : 予測に対応する潜在特徴量。パイプラインの `latents` 引数と互換性があります。形状は `numimages * numensemble × 4 × latentheight × latentwidth` です。

Marigold単眼深度推定パイプライン用の出力クラス。

#### diffusers.pipelines.marigold.MarigoldImageProcessor.visualize_depth[[diffusers.pipelines.marigold.MarigoldImageProcessor.visualize_depth]]

```python
diffusers.pipelines.marigold.MarigoldImageProcessor.visualize_depth(depth: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], val_min: float = 0.0, val_max: float = 1.0, color_map: str = 'Spectral')
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/marigold/marigold_image_processing.py#L387)

**パラメータ:**

depth (`PIL.Image.Image | np.ndarray | torch.Tensor | list[PIL.Image.Image, list[np.ndarray], : list[torch.Tensor]]`): 深度マップ。

val_min (`float`、*任意*、デフォルトは`0.0`) : 可視化される深度範囲の最小値。

val_max (`float`、*任意*、デフォルトは`1.0`) : 可視化される深度範囲の最大値。

color_map (`str`、*任意*、デフォルトは`"Spectral"`) : 単一チャネルの深度予測をカラー表現に変換するために使用されるカラーマップ。

`MarigoldDepthPipeline`の予測値などの深度マップを可視化します。

Returns: 深度マップの可視化を含む`list[PIL.Image.Image]`。

## Marigold Normals Estimation API[[diffusers.MarigoldNormalsPipeline]]

#### diffusers.MarigoldNormalsPipeline[[diffusers.MarigoldNormalsPipeline]]

```python
diffusers.MarigoldNormalsPipeline(unet: UNet2DConditionModel, vae: AutoencoderKL, scheduler: diffusers.schedulers.scheduling_ddim.DDIMScheduler | diffusers.schedulers.scheduling_lcm.LCMScheduler, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, prediction_type: str | None = None, use_full_z_range: bool | None = True, default_denoising_steps: int | None = None, default_processing_resolution: int | None = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py#L99)

**パラメータ:**

unet (`UNet2DConditionModel`) : 画像の潜在変数に条件付けられ、ノーマルの潜在変数のノイズ除去を行う条件付き U-Net。

vae (`AutoencoderKL`) : 画像と予測を潜在表現にエンコードおよびデコードするための Variational Auto-Encoder (VAE) モデル。

scheduler (`DDIMScheduler` または `LCMScheduler`) : `unet` と組み合わせて、エンコードされた画像の潜在変数からノイズを除去するために使用するスケジューラ。

text_encoder (`CLIPTextModel`) : 空のテキスト埋め込み用のテキストエンコーダー。

tokenizer (`CLIPTokenizer`) : CLIP トークナイザー。

prediction_type (`str`, *任意*) : モデルが生成する予測の型。

use_full_z_range (`bool`, *任意*) : このモデルが予測する法線が、Z 次元の全範囲を利用するか、正の半分のみを利用するかを示します。

default_denoising_steps (`int`, *optional*) : 指定されたモデルで、適切な品質の予測を生成するために必要な、デノイジング拡散ステップの最小値です。この値はモデルの config に設定する必要があります。パイプラインを呼び出す際に `num_inference_steps` を明示的に設定しない場合、デフォルト値が使用されます。これは、非常に短いデノイジングスケジュールに依存するもの（`LCMScheduler`）や、完全な拡散スケジュールを持つもの（`DDIMScheduler`）など、このパイプラインと互換性のあるさまざまなモデルのバリエーションで、適切な結果を得ることを保証するために必要です。

default_processing_resolution (`int`、*任意*) : パイプラインの `processing_resolution` パラメータの推奨値です。この値はモデルの config に設定する必要があります。パイプラインを呼び出す際に `processing_resolution` を明示的に設定しない場合、デフォルト値が使用されます。これは、最適な処理解像度の値が異なるように学習されたさまざまなモデルのバリエーションに対して、妥当な結果を得ることを保証するために必要です。

Marigold手法を用いた単眼法線推定のためのPipeline: https://marigoldmonodepth.github.io

このモデルは [DiffusionPipeline](/docs/diffusers/main/ja/api/pipelines/overview#diffusers.DiffusionPipeline) を継承しています。ライブラリがすべてのパイプラインに対して実装している汎用的なメソッド（ダウンロードや保存、特定のデバイスでの実行など）については、スーパークラスのドキュメントを参照してください。

#### __call__[[diffusers.MarigoldNormalsPipeline.__call__]]

```python
__call__(image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], num_inference_steps: int | None = None, ensemble_size: int = 1, processing_resolution: int | None = None, match_input_resolution: bool = True, resample_method_input: str = 'bilinear', resample_method_output: str = 'bilinear', batch_size: int = 1, ensembling_kwargs: dict[str, typing.Any] | None = None, latents: typing.Union[torch.Tensor, list[torch.Tensor], NoneType] = None, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, output_type: str = 'np', output_uncertainty: bool = False, output_latent: bool = False, return_dict: bool = True)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py#L332)

**パラメータ:**

image (`PIL.Image.Image`、`np.ndarray`、`torch.Tensor`、`list[PIL.Image.Image]`、`list[np.ndarray]`)、: `list[torch.Tensor]`: 法線推定タスクの入力として使用される入力画像です。配列やテンソルの場合、想定される値の範囲は`[0, 1]`です。4次元の配列またはテンソルを渡すことで、画像のバッチを渡すことができます。また、2次元または3次元の配列やテンソルからなる画像のリストを渡すことも可能です。後者の場合、リストのすべての要素は同じ幅と高さを有する必要があります。

num_inference_steps (`int`、*任意*、デフォルトは `None`) : 推論時のデノイジング拡散ステップ数。デフォルト値 `None` の場合、自動的に選択されます。

ensemble_size (`int`、デフォルトは `1`) : アンサンブル予測の数。値を大きくすると、測定可能な改善と視覚的な劣化が確認されます。

processing_resolution (`int`、*任意*、デフォルトは `None`) : 実際の処理解像度。`0` に設定すると、入力画像の大きい方の寸法に一致します。これにより予測がより鮮明になりますが、グローバルなコンテキスト全体が失われる可能性もあります。デフォルト値 `None` は、モデル設定から最適な値に解決されます。

match_input_resolution (`bool`、*任意*、デフォルトは`True`) : 有効な場合、出力予測は入力次元に合わせてリサイズされます。無効な場合、出力の長い辺は`processing_resolution`に等しくなります。

resample_method_input (`str`、*任意*、デフォルトは`"bilinear"`) : 入力画像を`processing_resolution`にリサイズするために使用されるリサンプリング手法です。受け入れられる値は、`"nearest"`、`"nearest-exact"`、`"bilinear"`、`"bicubic"`、または`"area"`です。

resample_method_output (`str`、*任意*、デフォルトは`"bilinear"`) : 出力予測を入力解像度に合わせるためにリサイズする際に使用するリサンプリング手法。受け入れられる値は`"nearest"`、`"nearest-exact"`、`"bilinear"`、`"bicubic"`、または`"area"`です。

batch_size (`int`、*任意*、デフォルトは `1`) : バッチサイズ。`ensemble_size` を設定するか、画像のテンソルを渡す場合にのみ関連します。

ensembling_kwargs (`dict`, *任意*, デフォルトは `None`) : 精密なアンサンブル制御のための引数を含む追加の辞書。以下のオプションが利用可能です: - reduction (`str`, *任意*, デフォルトは `"closest"`): 各ピクセル位置に適用されるアンサンブル関数を定義します。`"closest"` または `"mean"` のいずれかです。

latents (`torch.Tensor`、*任意*、デフォルトは`None`) : ランダム初期化に置き換えるための潜在ノイズテンソルです。これらは、直前の関数呼び出しの出力から取得できます。

generator (`torch.Generator`、または `list[torch.Generator]`、*任意*、デフォルトは `None`) : 再現性を確保するための乱数生成器オブジェクト。

output_type (`str`、*任意*、デフォルトは`"np"`) : 出力の`prediction`および任意の`uncertainty`フィールドの推奨フォーマット。受け入れられる値は、`"np"`（numpy配列）または`"pt"`（torchテンソル）です。

output_uncertainty (`bool`、*任意*、デフォルトは`False`) : 有効にすると、`ensemble_size`引数が2より大きい値に設定されている場合、出力の`uncertainty`フィールドに予測不確実性マップが含まれます。

output_latent (`bool`、*任意*、デフォルトは`False`) : 有効にすると、出力の`latent`フィールドには、アンサンブル内の予測に対応する潜在コードが含まれます。これらのコードは保存・変更でき、`latents`引数を用いた後続の呼び出しに使用できます。

return_dict (`bool`、*任意*、デフォルトは`True`) : プレーンなタプルではなく、[MarigoldNormalsOutput](/docs/diffusers/main/ja/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldNormalsOutput)を返すかどうか。

**戻り値:** [MarigoldNormalsOutput](/docs/diffusers/main/ja/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldNormalsOutput) または `tuple`

`return_dict` が `True` の場合、[MarigoldNormalsOutput](/docs/diffusers/main/ja/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldNormalsOutput) が返され、それ以外の場合は `tuple` が返されます。このとき、最初の要素は予測値、2番目の要素は不確実性（または `None`）、3番目の要素は潜在変数（または `None`）です。

パイプラインを呼び出したときに実行される関数。

例:
```py
>>> import diffusers
>>> import torch

>>> pipe = diffusers.MarigoldNormalsPipeline.from_pretrained(
...     "prs-eth/marigold-normals-v1-1", variant="fp16", torch_dtype=torch.float16
... ).to("cuda")

>>> image = diffusers.utils.load_image("https://marigoldmonodepth.github.io/images/einstein.jpg")
>>> normals = pipe(image)

>>> vis = pipe.image_processor.visualize_normals(normals.prediction)
>>> vis[0].save("einstein_normals.png")
```

#### diffusers.pipelines.marigold.MarigoldNormalsOutput[[diffusers.pipelines.marigold.MarigoldNormalsOutput]]

```python
diffusers.pipelines.marigold.MarigoldNormalsOutput(prediction: typing.Union[numpy.ndarray, torch.Tensor], uncertainty: typing.Union[NoneType, numpy.ndarray, torch.Tensor], latent: typing.Optional[torch.Tensor])
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py#L78)

**パラメータ:**

prediction (`np.ndarray`、`torch.Tensor`) : 値が [-1, 1] の範囲にある予測された法線ベクトル。`torch.Tensor` の場合は形状が `numimages × 3 × height × width`、`np.ndarray` の場合は `numimages × height × width × 3` です。

uncertainty (`None`, `np.ndarray`, `torch.Tensor`) : アンサンブルから計算された不確実性マップ。値は [0, 1] の範囲です。`torch.Tensor` の場合、形状は `numimages × 1 × height × width` であり、`np.ndarray` の場合は `numimages × height × width × 1` です。

latent (`None`, `torch.Tensor`) : 予測に対応する潜在特徴量。パイプラインの `latents` 引数と互換性があります。形状は `numimages * numensemble × 4 × latentheight × latentwidth` です。

Marigold単眼法線予測パイプライン用の出力クラス。

#### diffusers.pipelines.marigold.MarigoldImageProcessor.visualize_normals[[diffusers.pipelines.marigold.MarigoldImageProcessor.visualize_normals]]

```python
diffusers.pipelines.marigold.MarigoldImageProcessor.visualize_normals(normals: typing.Union[numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor]], flip_x: bool = False, flip_y: bool = False, flip_z: bool = False)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/marigold/marigold_image_processing.py#L486)

**パラメータ:**

normals (`np.ndarray | torch.Tensor | list[np.ndarray, list[torch.Tensor]]`) : 表面法線ベクトル。

flip_x (`bool`、*任意*、デフォルトは`False`) : 法線座標系の X 軸を反転します。デフォルトの向きは右です。

flip_y (`bool`、*任意*、デフォルトは `False`) : 法線座標系の Y 軸を反転します。デフォルトの方向は上です。

flip_z (`bool`、*任意*、デフォルトは`False`) : 法線座標系の Z 軸を反転します。デフォルトの向きは観察者に向いています。

`MarigoldNormalsPipeline` の予測値などの法線ベクトルを可視化します。

戻り値: `list[PIL.Image.Image]` 表面法線の可視化を含むリスト。

## Marigold 固有画像分解 API[[diffusers.MarigoldIntrinsicsPipeline]]

#### diffusers.MarigoldIntrinsicsPipeline[[diffusers.MarigoldIntrinsicsPipeline]]

```python
diffusers.MarigoldIntrinsicsPipeline(unet: UNet2DConditionModel, vae: AutoencoderKL, scheduler: diffusers.schedulers.scheduling_ddim.DDIMScheduler | diffusers.schedulers.scheduling_lcm.LCMScheduler, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, prediction_type: str | None = None, target_properties: dict[str, typing.Any] | None = None, default_denoising_steps: int | None = None, default_processing_resolution: int | None = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/marigold/pipeline_marigold_intrinsics.py#L120)

**パラメータ:**

unet (`UNet2DConditionModel`) : 画像の潜在変数に条件付けられ、ターゲットの潜在変数からノイズを除去するための条件付き U-Net。

vae (`AutoencoderKL`) : 画像と予測を潜在表現にエンコードおよびデコードするための Variational Auto-Encoder (VAE) モデル。

scheduler (`DDIMScheduler` または `LCMScheduler`) : `unet` と組み合わせて、エンコードされた画像の潜在変数からノイズを除去するために使用するスケジューラ。

text_encoder (`CLIPTextModel`) : 空のテキスト埋め込み用のテキストエンコーダー。

tokenizer (`CLIPTokenizer`) : CLIP トークナイザー。

prediction_type (`str`, *任意*) : モデルが生成する予測の型。

target_properties (`dict[str, Any]`, *任意*) : 予測されたモーダリティの属性。予測されたモーダリティの数、順序、名前を定義するために使用される`list[str]`型の`target_names`や、予測を解釈するために必要なその他のメタデータなど。

default_denoising_steps (`int`, *optional*) : 指定されたモデルで、適切な品質の予測を生成するために必要な、デノイジング拡散ステップの最小値です。この値はモデルの config に設定する必要があります。パイプラインを呼び出す際に `num_inference_steps` を明示的に設定しない場合、デフォルト値が使用されます。これは、非常に短いデノイジングスケジュールに依存するもの（`LCMScheduler`）や、完全な拡散スケジュールを持つもの（`DDIMScheduler`）など、このパイプラインと互換性のあるさまざまなモデルのバリエーションで、適切な結果を得ることを保証するために必要です。

default_processing_resolution (`int`、*任意*) : パイプラインの `processing_resolution` パラメータの推奨値です。この値はモデルの config に設定する必要があります。パイプラインを呼び出す際に `processing_resolution` を明示的に設定しない場合、デフォルト値が使用されます。これは、最適な処理解像度の値が異なるように学習されたさまざまなモデルのバリエーションに対して、妥当な結果を得ることを保証するために必要です。

Marigold手法を用いた固有画像分解（IID）のパイプライン: https://marigoldcomputervision.github.io

このモデルは [DiffusionPipeline](/docs/diffusers/main/ja/api/pipelines/overview#diffusers.DiffusionPipeline) を継承しています。ライブラリがすべてのパイプラインに対して実装している汎用的なメソッド（ダウンロードや保存、特定のデバイスでの実行など）については、スーパークラスのドキュメントを参照してください。

#### __call__[[diffusers.MarigoldIntrinsicsPipeline.__call__]]

```python
__call__(image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], num_inference_steps: int | None = None, ensemble_size: int = 1, processing_resolution: int | None = None, match_input_resolution: bool = True, resample_method_input: str = 'bilinear', resample_method_output: str = 'bilinear', batch_size: int = 1, ensembling_kwargs: dict[str, typing.Any] | None = None, latents: typing.Union[torch.Tensor, list[torch.Tensor], NoneType] = None, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, output_type: str = 'np', output_uncertainty: bool = False, output_latent: bool = False, return_dict: bool = True)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/marigold/pipeline_marigold_intrinsics.py#L359)

**パラメータ:**

image (`PIL.Image.Image`、`np.ndarray`、`torch.Tensor`、`list[PIL.Image.Image]`、`list[np.ndarray]`)、: `list[torch.Tensor]`: 固有成分分解タスクの入力として使用される入力画像です。配列やテンソルの場合、想定される値の範囲は`[0, 1]`です。4次元の配列またはテンソルを渡すことで、画像のバッチを渡すことができます。また、2次元または3次元の配列またはテンソルからなる画像のリストを渡すことも可能です。後者の場合、リストのすべての要素は同じ幅と高さを有する必要があります。

num_inference_steps (`int`、*任意*、デフォルトは `None`) : 推論時のデノイジング拡散ステップ数。デフォルト値 `None` の場合、自動的に選択されます。

ensemble_size (`int`、デフォルトは `1`) : アンサンブル予測の数。値を大きくすると、測定可能な改善と視覚的な劣化が確認されます。

processing_resolution (`int`、*任意*、デフォルトは `None`) : 実際の処理解像度。`0` に設定すると、入力画像の大きい方の寸法に一致します。これにより予測がより鮮明になりますが、グローバルなコンテキスト全体が失われる可能性もあります。デフォルト値 `None` は、モデル設定から最適な値に解決されます。

match_input_resolution (`bool`、*任意*、デフォルトは`True`) : 有効な場合、出力予測は入力次元に合わせてリサイズされます。無効な場合、出力の長い辺は`processing_resolution`に等しくなります。

resample_method_input (`str`、*任意*、デフォルトは`"bilinear"`) : 入力画像を`processing_resolution`にリサイズするために使用されるリサンプリング手法です。受け入れられる値は、`"nearest"`、`"nearest-exact"`、`"bilinear"`、`"bicubic"`、または`"area"`です。

resample_method_output (`str`、*任意*、デフォルトは`"bilinear"`) : 出力予測を入力解像度に合わせるためにリサイズする際に使用するリサンプリング手法。受け入れられる値は`"nearest"`、`"nearest-exact"`、`"bilinear"`、`"bicubic"`、または`"area"`です。

batch_size (`int`、*任意*、デフォルトは `1`) : バッチサイズ。`ensemble_size` を設定するか、画像のテンソルを渡す場合にのみ関連します。

ensembling_kwargs (`dict`、*任意*、デフォルトは `None`) : 精密なアンサンブル制御のための引数を含む追加の辞書。利用可能なオプションは以下の通りです: - reduction (`str`、*任意*、デフォルトは `"median"`): 各ピクセル位置に適用されるアンサンブル関数を定義します。`"median"` または `"mean"` のいずれかを選択できます。

latents (`torch.Tensor`、*任意*、デフォルトは`None`) : ランダム初期化に置き換えるための潜在ノイズテンソルです。これらは、直前の関数呼び出しの出力から取得できます。

generator (`torch.Generator`、または `list[torch.Generator]`、*任意*、デフォルトは `None`) : 再現性を確保するための乱数生成器オブジェクト。

output_type (`str`、*任意*、デフォルトは`"np"`) : 出力の`prediction`および任意の`uncertainty`フィールドの推奨フォーマット。受け入れられる値は、`"np"`（numpy配列）または`"pt"`（torchテンソル）です。

output_uncertainty (`bool`、*任意*、デフォルトは`False`) : 有効にすると、`ensemble_size`引数が2より大きい値に設定されている場合、出力の`uncertainty`フィールドに予測不確実性マップが含まれます。

output_latent (`bool`、*任意*、デフォルトは`False`) : 有効にすると、出力の`latent`フィールドには、アンサンブル内の予測に対応する潜在コードが含まれます。これらのコードは保存・変更でき、`latents`引数を用いた後続の呼び出しに使用できます。

return_dict (`bool`、*任意*、デフォルトは `True`) : プレーンなタプルではなく [MarigoldIntrinsicsOutput](/docs/diffusers/main/ja/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldIntrinsicsOutput) を返すかどうか。

**戻り値:** [MarigoldIntrinsicsOutput](/docs/diffusers/main/ja/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldIntrinsicsOutput) または `tuple`

`return_dict` が `True` の場合、[MarigoldIntrinsicsOutput](/docs/diffusers/main/ja/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldIntrinsicsOutput) が返され、それ以外の場合は `tuple` が返されます。このとき、最初の要素は予測値、2番目の要素は不確実性（または `None`）、3番目の要素は潜在変数（または `None`）です。

パイプラインを呼び出したときに実行される関数。

例:
```py
>>> import diffusers
>>> import torch

>>> pipe = diffusers.MarigoldIntrinsicsPipeline.from_pretrained(
...     "prs-eth/marigold-iid-appearance-v1-1", variant="fp16", torch_dtype=torch.float16
... ).to("cuda")

>>> image = diffusers.utils.load_image("https://marigoldmonodepth.github.io/images/einstein.jpg")
>>> intrinsics = pipe(image)

>>> vis = pipe.image_processor.visualize_intrinsics(intrinsics.prediction, pipe.target_properties)
>>> vis[0]["albedo"].save("einstein_albedo.png")
>>> vis[0]["roughness"].save("einstein_roughness.png")
>>> vis[0]["metallicity"].save("einstein_metallicity.png")
```

```py
>>> import diffusers
>>> import torch

>>> pipe = diffusers.MarigoldIntrinsicsPipeline.from_pretrained(
...     "prs-eth/marigold-iid-lighting-v1-1", variant="fp16", torch_dtype=torch.float16
... ).to("cuda")

>>> image = diffusers.utils.load_image("https://marigoldmonodepth.github.io/images/einstein.jpg")
>>> intrinsics = pipe(image)

>>> vis = pipe.image_processor.visualize_intrinsics(intrinsics.prediction, pipe.target_properties)
>>> vis[0]["albedo"].save("einstein_albedo.png")
>>> vis[0]["shading"].save("einstein_shading.png")
>>> vis[0]["residual"].save("einstein_residual.png")
```

#### diffusers.pipelines.marigold.MarigoldIntrinsicsOutput[[diffusers.pipelines.marigold.MarigoldIntrinsicsOutput]]

```python
diffusers.pipelines.marigold.MarigoldIntrinsicsOutput(prediction: typing.Union[numpy.ndarray, torch.Tensor], uncertainty: typing.Union[NoneType, numpy.ndarray, torch.Tensor], latent: typing.Optional[torch.Tensor])
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/marigold/pipeline_marigold_intrinsics.py#L96)

**パラメータ:**

prediction (`np.ndarray`、`torch.Tensor`) : 値が [0, 1] の範囲にある予測された画像の内部パラメータ。`torch.Tensor` の場合は `(numimages * numtargets) × 3 × height × width`、`np.ndarray` の場合は `(numimages * numtargets) × height × width × 3` の形状を持ちます。ここで、`numtargets` は、内部画像分解の予測されるターゲットモダリティの数に対応します。

uncertainty (`None`, `np.ndarray`, `torch.Tensor`) : アンサンブルから計算された不確実性マップ。値は [0, 1] の範囲です。`torch.Tensor` の場合、形状は `(numimages * numtargets) × 3 × height × width`、`np.ndarray` の場合、形状は `(numimages * numtargets) × height × width × 3` です。

latent (`None`, `torch.Tensor`) : 予測に対応する潜在特徴量。パイプラインの `latents` 引数と互換性があります。形状は `(numimages * numensemble) × (numtargets * 4) × latentheight × latentwidth` です。

Marigold Intrinsic Image Decomposition パイプライン用の出力クラスです。

#### diffusers.pipelines.marigold.MarigoldImageProcessor.visualize_intrinsics[[diffusers.pipelines.marigold.MarigoldImageProcessor.visualize_intrinsics]]

```python
diffusers.pipelines.marigold.MarigoldImageProcessor.visualize_intrinsics(prediction: typing.Union[numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor]], target_properties: dict, color_map: str | dict[str, str] = 'binary')
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/marigold/marigold_image_processing.py#L542)

**パラメータ:**

prediction (`np.ndarray | torch.Tensor | list[np.ndarray, list[torch.Tensor]]`) : 固有画像分解。

target_properties (`dict[str, Any]`) : 分解プロパティ。期待されるエントリ: `target_names: list[str]` および、キーが `prediction_space: str`、`sub_target_names: list[str | Null]`（3 つのエントリが必要で、欠損モードは null）、`up_to_scale: bool` である辞書。各ターゲットおよびサブターゲットごとに 1 つ。

color_map (`str | dict[str, str]`、*任意*、デフォルトは `"Spectral"`) : 単一チャネルの予測値をカラー表現に変換するために使用されるカラーマップ。辞書が渡された場合、各モダリティに独自のカラーマップを適用できます。

`MarigoldIntrinsicsPipeline` の予測など、固有画像分解を可視化します。

Returns: 固有画像分解の可視化を含む`list[dict[str, PIL.Image.Image]]`

