# 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 口头报告论文 [Repurposing Diffusion-Based Image Generators for Monocular Depth Estimation](https://huggingface.co/papers/2312.02145) 中提出。其核心思想是**将文本到图像潜在扩散模型（LDMs）的生成先验重新用于传统计算机视觉任务**。该方案通过对 Stable Diffusion 进行微调以应用于**单目深度估计**，如上文中的示意图所示。

Marigold 在后续论文 [Marigold: Affordable Adaptation of Diffusion-Based Image Generators for Image Analysis](https://huggingface.co/papers/2312.02145) 中得到了进一步扩展，该论文由 [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 扩展以支持 **Surface Normals** 和 **Intrinsic Image Decomposition**（IID）等新模态，引入了针对 **Latent Consistency Models**（LCM）的训练协议，并展示了 **High-Resolution**（HR）处理能力。

> [!TIP]
> 早期的 Marigold 模型（`v1-0` 及更早版本）针对至少 10 个推理步骤进行了优化，以获得最佳效果。后来开发的 LCM 模型能够在仅 1 到 4 个步骤内实现高质量推理。从 `v1-1` 及之后的 Marigold 模型使用 DDIM 调度器，可在最少 1 到 4 个步骤内达到最优效果。

## 可用流水线

每个流水线都针对特定的计算机视觉任务进行了定制，用于处理输入的 RGB 图像并生成相应的预测。目前，已实现以下计算机视觉任务：

| Pipeline                                                                                                                                          | 推荐的模型检查点                                                                                                                                                                           |                              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 流水线及 [original codebase](https://github.com/prs-eth/marigold) 使用而设计，后者也可用于训练新的模型检查点。以下是推荐检查点的汇总，它们均能在 1 到 4 步内产生可靠的结果。

| 检查点                                                                                          | 模态     | 评论                                                                                                                                                                              |
|-----------------------------------------------------------------------------------------------------|--------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [prs-eth/marigold-depth-v1-1](https://huggingface.co/prs-eth/marigold-depth-v1-1)                   | 深度        | 仿射不变深度预测为每个像素分配一个介于 0（近平面）和 1（远平面）之间的值，这两个平面均由模型在推理过程中确定。                    |
| [prs-eth/marigold-normals-v0-1](https://huggingface.co/prs-eth/marigold-normals-v0-1)               | 法线      | 表面法线预测值是屏幕空间相机坐标系下的单位长度 3D 向量，其取值范围为 -1 到 1。                                                        |
| [prs-eth/marigold-iid-appearance-v1-1](https://huggingface.co/prs-eth/marigold-iid-appearance-v1-1) | 内置函数   | InteriorVerse 分解由 Albedo 以及两个 BRDF 材质属性组成：Roughness 和 Metallicity。                                                                      |
| [prs-eth/marigold-iid-lighting-v1-1](https://huggingface.co/prs-eth/marigold-iid-lighting-v1-1)     | 内置函数   | 图像 $I$ 的 HyperSim 分解由反照率 $A$、漫反射着色 $S$ 和非漫反射残差 $R$ 组成：$I = A*S+R$。 |

> [!TIP]
> 请务必查阅调度器（Schedulers）[指南](../../using-diffusers/schedulers)，了解如何探索调度器速度与质量之间的权衡，并参阅[跨流水线复用组件](../../using-diffusers/loading#reusing-models-in-multiple-pipelines)部分，学习如何高效地将相同组件加载到多个流水线中。此外，如需进一步了解如何降低此流水线的内存占用，请参阅[此处](./stable_diffusion/svd#reduce-memory-usage)的["减少内存占用"]部分。

> [!WARNING]
> Marigold 流水线在设计时，调度器（scheduler）是嵌入在模型检查点中的。不同调度器所需的最优推理步数各不相同，不存在一个在所有情况下都表现最佳的通用值。为此，流水线 `__call__` 方法中的 `num_inference_steps` 参数默认值为 `None`（参见 API 参考）。除非显式设置，否则该参数会从检查点配置文件（`model_index.json`）中的 `default_denoising_steps` 字段继承其值。这确保了仅传入 `image` 参数调用流水线时，仍能获得高质量的预测结果。

以下示例主要基于深度预测，但同样适用于其他受支持的模态。我们使用 Midjourney 生成的同一张爱因斯坦输入图像来展示预测结果，以便更容易地比较不同模态和检查点之间的预测可视化效果。

  
    
    
      所有 Marigold 流水线的示例输入图像
    
  

## 深度预测

要获取深度预测，请将 `prs-eth/marigold-depth-v1-1` 检查点加载到 [MarigoldDepthPipeline](/docs/diffusers/v0.43.0/zh/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/v0.43.0/zh/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldImageProcessor.visualize_depth) 函数会应用 [matplotlib 的 colormap](https://matplotlib.org/stable/users/explain/colors/colormaps.html)（默认为 `Spectral`），将单通道 `[0, 1]` 深度范围内的预测像素值映射为 RGB 图像。使用 `Spectral` colormap 时，深度较近的像素显示为红色，较远的像素显示为蓝色。16 位 PNG 文件存储的是从 `[0, 1]` 范围线性映射到 `[0, 65535]` 的单通道值。以下是原始预测和可视化后的预测。在可视化结果中，较暗且较近的区域（胡子）更容易被区分。

  
    
    
      预测深度（16 位 PNG）
    
  
  
    
    
      预测深度可视化（光谱）
    
  

## 表面法线估计

将 `prs-eth/marigold-normals-v1-1` 检查点加载到 [MarigoldNormalsPipeline](/docs/diffusers/v0.43.0/zh/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/v0.43.0/zh/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldImageProcessor.visualize_normals) 将三维预测值（像素值范围为 `[-1, 1]`）映射为 RGB 图像。该可视化函数支持翻转表面法线的坐标轴，以便与其他坐标系选择兼容。从概念上讲，每个像素根据其所在参考系中的表面法线向量进行着色，其中 `X` 轴指向右侧，`Y` 轴指向上方，`Z` 轴指向观察者。以下是可视化后的预测结果：

  
    
    
      预测表面法线可视化
    
  

在此示例中，鼻尖几乎肯定有一个表面点，其表面法向量正对着观察者，这意味着它的坐标为 `[0, 0, 1]`。该向量映射到 RGB `[128, 128, 255]`，对应于紫蓝色。类似地，图像右侧脸颊上的表面法向量具有较大的 `X` 分量，从而增加了红色色调。肩部指向上方且具有较大 `Y` 分量的点会促进绿色色调。

## 本征图像分解

Marigold 提供了两个用于本征图像分解（IID）的模型：“Appearance”和“Lighting”。每个模型分别基于 InteriorVerse 和 Hypersim 的标注生成 Albedo 图。

- “外观”模型还会估计材质属性：粗糙度和金属度。
- “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 与线性空间）存储在 `pipe.target_properties` 字典中，该字典会被传入 [visualize_intrinsics()](/docs/diffusers/v0.43.0/zh/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldImageProcessor.visualize_intrinsics) 函数。

以下是一些展示预测分解结果的示例。所有模态都可以在 [Intrinsic Image Decomposition](https://huggingface.co/spaces/prs-eth/marigold-iid) Space 中查看。

  
    
    
      预测反照率（“外观”模型）
    
  
  
    
    
      预测的漫反射着色（“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 执行单步去噪。最后，预测潜变量通过 VAE 解码器解码到像素空间。在此配置中，三个模块调用中有两个专门用于在 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)
```

到目前为止，我们已经优化了扩散步数和模型组件。自注意力操作占据了计算量的很大一部分。通过使用更高效的注意力处理器，可以加速这些操作：

```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`可以进一步提升性能。然而，编译会在首次调用 pipeline 时产生显著的开销，因此只有在同一 pipeline 实例被反复调用时（例如在循环中）才具有优势。

```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 独立应用于输入视频帧
  

为了解决这个问题，可以向 pipeline 传递 `latents` 参数，以定义扩散的起始点。经验表明，将完全相同的起始点噪声 latent 与对应于上一帧预测的 latent 进行凸组合，可以得到足够平滑的结果，如下面的代码片段所示：

```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 生成
    
  

## 定量评估

要在标准排行榜和基准测试（例如 NYU、KITTI 及其他数据集）中对 Marigold 进行定量评估，请遵循论文中概述的评估协议：加载全精度 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")
```

  
    
    
      深度不确定性
    
  
  
    
    
      表面法线不确定性
    
  
  
    
    
      反照率不确定性
    
  

不确定性的解释很简单：较高的值（白色）对应于模型难以做出一致预测的像素。
- 深度模型在物体深度发生突变的边缘处表现出最大的不确定性。
- 表面法线模型在头发等细粒度结构以及诸如
领口区域。
- Albedo 不确定性以 RGB 图像的形式表示，因为它独立地捕获每个颜色通道的不确定性，
与深度和表面法线不同。它在阴影区域和不连续处的值也更高。

## Marigold 深度预测 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/v0.43.0/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py#L104)

**参数：**

unet (`UNet2DConditionModel`)：用于对深度潜在变量进行去噪的条件 U-Net，以图像潜在变量作为条件。

vae (`AutoencoderKL`)：变分自编码器（VAE）模型，用于将图像编码为潜在表示，以及从潜在表示解码出图像和预测结果。

scheduler (`DDIMScheduler` 或 `LCMScheduler`)：用于与 `unet` 配合，对编码后的图像潜在表示进行去噪的调度器。

text_encoder (`CLIPTextModel`)：文本编码器，用于空文本嵌入。

tokenizer (`CLIPTokenizer`)：CLIP 分词器。

prediction_type (`str`，*可选*)：模型所做预测的类型。

scale_invariant (`bool`，*可选*)：一个模型属性，用于指定预测的深度图是否具有尺度不变性。此值必须在模型配置中设置。当与 `shift_invariant=True` 标志一起使用时，该模型也被称为“仿射不变”。注意：不支持覆盖此值。

shift_invariant (`bool`，*可选*)：一个模型属性，用于指定预测的深度图是否具有平移不变性。此值必须在模型配置中设置。当与 `scale_invariant=True` 标志一起使用时，该模型也被称为“仿射不变”。注意：不支持覆盖此值。

default_denoising_steps (`int`, *可选*) : 使用给定模型生成合理质量预测所需的最少去噪扩散步数。此值必须在模型配置中设置。当调用流水线时未显式设置 `num_inference_steps`，将使用默认值。此参数是必需的，以确保与流水线兼容的各种模型变体（例如依赖极短去噪调度的 `LCMScheduler` 和具有完整扩散调度的 `DDIMScheduler`）都能获得合理的结果。

default_processing_resolution (`int`, *optional*) : 流水线中 `processing_resolution` 参数的推荐值。此值必须在模型配置中设置。当调用流水线时未显式设置 `processing_resolution`，将使用默认值。这是为了确保在使用以不同最佳处理分辨率值训练的各种模型变体时，能够获得合理的结果。

使用 Marigold 方法进行单目深度估计的 Pipeline：https://marigoldmonodepth.github.io。

该模型继承自 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。请查阅父类文档，了解该库为所有 pipeline 实现的通用方法（例如下载或保存、在特定设备上运行等）。

#### __调用__[[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/v0.43.0/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]`。可以通过提供四维数组或张量来传入一批图像。此外，还可以传入由二维或三维数组或张量组成的图像列表。在后一种情况下，列表中所有元素的宽度和高度必须相同。

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`)：启用后，输出的 `uncertainty` 字段将包含预测不确定性图，前提是 `ensemble_size` 参数被设置为大于 2 的值。

output_latent (`bool`，*可选*，默认为 `False`)：启用后，输出的 `latent` 字段将包含对应于集成内预测的潜在编码。这些编码可以被保存、修改，并在后续调用中通过 `latents` 参数使用。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 [MarigoldDepthOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldDepthOutput) 而不是普通元组。

**返回：** [MarigoldDepthOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldDepthOutput) 或 `tuple`

如果 `return_dict` 为 `True`，则返回 [MarigoldDepthOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldDepthOutput)；否则返回一个 `tuple`，其中第一个元素是预测值，第二个元素是不确定性（或 `None`），第三个元素是潜在表示（或 `None`）。

调用 pipeline 时调用的函数。

示例：
```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/v0.43.0/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`) : 与预测对应的潜在特征，兼容于 pipeline 的 `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/v0.43.0/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` 的预测结果。

返回：`list[PIL.Image.Image]`，包含深度图的可视化结果。

## Marigold 法线估计 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/v0.43.0/src/diffusers/pipelines/marigold/pipeline_marigold_normals.py#L99)

**参数：**

unet (`UNet2DConditionModel`)：条件 U-Net，用于对法线潜在变量进行去噪，并以图像潜在变量作为条件。

vae (`AutoencoderKL`)：变分自编码器（VAE）模型，用于将图像编码为潜在表示，以及从潜在表示解码出图像和预测结果。

scheduler (`DDIMScheduler` 或 `LCMScheduler`)：用于与 `unet` 配合，对编码后的图像潜在表示进行去噪的调度器。

text_encoder (`CLIPTextModel`)：文本编码器，用于空文本嵌入。

tokenizer (`CLIPTokenizer`)：CLIP 分词器。

prediction_type (`str`，*可选*)：模型所做预测的类型。

use_full_z_range (`bool`，*可选*)：该模型预测的法线是否利用 Z 维度的完整范围，还是仅使用其正半部分。

default_denoising_steps (`int`, *可选*) : 使用给定模型生成合理质量预测所需的最少去噪扩散步数。此值必须在模型配置中设置。当调用流水线时未显式设置 `num_inference_steps`，将使用默认值。此参数是必需的，以确保与流水线兼容的各种模型变体（例如依赖极短去噪调度的 `LCMScheduler` 和具有完整扩散调度的 `DDIMScheduler`）都能获得合理的结果。

default_processing_resolution (`int`, *optional*) : 流水线中 `processing_resolution` 参数的推荐值。此值必须在模型配置中设置。当调用流水线时未显式设置 `processing_resolution`，将使用默认值。这是为了确保在使用以不同最佳处理分辨率值训练的各种模型变体时，能够获得合理的结果。

使用 Marigold 方法进行单目法线估计的 Pipeline：https://marigoldmonodepth.github.io。

该模型继承自 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。请查阅父类文档，了解该库为所有 pipeline 实现的通用方法（例如下载或保存、在特定设备上运行等）。

#### __调用__[[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/v0.43.0/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]`。可以通过提供四维数组或张量来传入一批图像。此外，还可以传入由二维或三维数组或张量组成的图像列表。在后一种情况下，列表中所有元素的宽度和高度必须相同。

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`) : 用于精确控制集成（ensembling）的额外参数字典。可用选项如下： - 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`)：启用后，输出的 `uncertainty` 字段将包含预测不确定性图，前提是 `ensemble_size` 参数被设置为大于 2 的值。

output_latent (`bool`，*可选*，默认为 `False`)：启用后，输出的 `latent` 字段将包含对应于集成内预测的潜在编码。这些编码可以被保存、修改，并在后续调用中通过 `latents` 参数使用。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 [MarigoldNormalsOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldNormalsOutput) 而不是普通元组。

**返回：** [MarigoldNormalsOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldNormalsOutput) 或 `tuple`

如果 `return_dict` 为 `True`，则返回 [MarigoldNormalsOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldNormalsOutput)；否则返回一个 `tuple`，其中第一个元素是预测值，第二个元素是不确定性（或 `None`），第三个元素是潜在表示（或 `None`）。

调用 pipeline 时调用的函数。

示例：
```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/v0.43.0/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`) : 与预测对应的潜在特征，兼容于 pipeline 的 `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/v0.43.0/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/v0.43.0/src/diffusers/pipelines/marigold/pipeline_marigold_intrinsics.py#L120)

**参数：**

unet (`UNet2DConditionModel`)：条件 U-Net，用于在图像潜变量的条件下对目标潜变量进行去噪。

vae (`AutoencoderKL`)：变分自编码器（VAE）模型，用于将图像编码为潜在表示，以及从潜在表示解码出图像和预测结果。

scheduler (`DDIMScheduler` 或 `LCMScheduler`)：用于与 `unet` 配合，对编码后的图像潜在表示进行去噪的调度器。

text_encoder (`CLIPTextModel`)：文本编码器，用于空文本嵌入。

tokenizer (`CLIPTokenizer`)：CLIP 分词器。

prediction_type (`str`，*可选*)：模型所做预测的类型。

target_properties (`dict[str, Any]`, *可选*) : 预测模态的属性，例如 `target_names`（一个 `list[str]`，用于定义预测模态的数量、顺序和名称），以及解释预测结果可能需要的其他元数据。

default_denoising_steps (`int`, *可选*) : 使用给定模型生成合理质量预测所需的最少去噪扩散步数。此值必须在模型配置中设置。当调用流水线时未显式设置 `num_inference_steps`，将使用默认值。此参数是必需的，以确保与流水线兼容的各种模型变体（例如依赖极短去噪调度的 `LCMScheduler` 和具有完整扩散调度的 `DDIMScheduler`）都能获得合理的结果。

default_processing_resolution (`int`, *optional*) : 流水线中 `processing_resolution` 参数的推荐值。此值必须在模型配置中设置。当调用流水线时未显式设置 `processing_resolution`，将使用默认值。这是为了确保在使用以不同最佳处理分辨率值训练的各种模型变体时，能够获得合理的结果。

使用 Marigold 方法进行本征图像分解（IID）的 Pipeline：https://marigoldcomputervision.github.io。

该模型继承自 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。请查阅父类文档，了解该库为所有 pipeline 实现的通用方法（例如下载或保存、在特定设备上运行等）。

#### __调用__[[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/v0.43.0/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]`。可以通过提供四维数组或张量来传入一批图像。此外，也可以传入由二维或三维数组或张量组成的图像列表。在后一种情况下，列表中所有元素的宽度和高度必须相同。

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`)：启用后，输出的 `uncertainty` 字段将包含预测不确定性图，前提是 `ensemble_size` 参数被设置为大于 2 的值。

output_latent (`bool`，*可选*，默认为 `False`)：启用后，输出的 `latent` 字段将包含对应于集成内预测的潜在编码。这些编码可以被保存、修改，并在后续调用中通过 `latents` 参数使用。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 [MarigoldIntrinsicsOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldIntrinsicsOutput) 而非普通元组。

**返回：** [MarigoldIntrinsicsOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldIntrinsicsOutput) 或 `tuple`

如果 `return_dict` 为 `True`，则返回 [MarigoldIntrinsicsOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/marigold#diffusers.pipelines.marigold.MarigoldIntrinsicsOutput)；否则返回一个 `tuple`，其中第一个元素是预测值，第二个元素是不确定性（或 `None`），第三个元素是潜在表示（或 `None`）。

调用 pipeline 时调用的函数。

示例：
```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/v0.43.0/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`) : 与预测对应的潜在特征，兼容 pipeline 的 `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[str, typing.Any], color_map: str | dict[str, str] = 'binary')
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/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`，每个目标和子目标各对应一个。

color_map (`str | dict[str, str]`，*可选*，默认为 `"Spectral"`)：用于将单通道预测值转换为彩色表示的色图。当传入字典时，可以为每种模态指定各自的色图。

可视化内在图像分解，例如 `MarigoldIntrinsicsPipeline` 的预测结果。

返回：`list[dict[str, PIL.Image.Image]]`，包含本征图像分解的可视化结果。

