Diffusers documentation
Marigold 计算机视觉
Marigold 计算机视觉

Marigold 在 Repurposing Diffusion-Based Image Generators for Monocular Depth Estimation 中提出,这是一篇由 Bingxin Ke、Anton Obukhov、Shengyu Huang、Nando Metzger、Rodrigo Caye Daudt 和 Konrad Schindler 撰写的 CVPR 2024 口头报告论文。其核心思想是将文本到图像潜在扩散模型(LDMs)的生成先验重新用于传统计算机视觉任务。该方法通过对 Stable Diffusion 进行微调以探索单目深度估计,如上文中的示意图所示。
Marigold 在后续论文 Marigold: Affordable Adaptation of Diffusion-Based Image Generators for Image Analysis 中得到了进一步扩展,作者为 Bingxin Ke、Kevin Qu、Tianfu Wang、Nando Metzger、Shengyu Huang、Bo Li、Anton Obukhov 和 Konrad Schindler。该工作将 Marigold 扩展以支持 Surface Normals 和 Intrinsic Image Decomposition(IID)等新模态,引入了针对 Latent Consistency Models(LCM)的训练协议,并展示了 High-Resolution(HR)处理能力。
早期的 Marigold 模型(
v1-0及更早版本)针对至少 10 个推理步骤进行了优化,以获得最佳效果。 后来开发的 LCM 模型能够在仅 1 到 4 个步骤内实现高质量推理。v1-1及之后的 Marigold 模型使用 DDIM 调度器,在最少 1 到 4 个步骤内即可达到最佳效果。
可用流水线
每个流水线都针对特定的计算机视觉任务进行了定制,用于处理输入的 RGB 图像并生成相应的预测结果。 目前,已实现以下计算机视觉任务:
可用检查点
所有原始检查点均可在 Hugging Face 的 PRS-ETH 组织下获取。 它们专为配合 diffusers 流水线以及 original codebase 使用而设计,后者也可用于训练新的模型检查点。 以下是推荐检查点的汇总,它们均可在 1 到 4 步内产生可靠的结果。
| 检查点 | 模态 | 评论 |
|---|---|---|
| prs-eth/marigold-depth-v1-1 | 深度 | 仿射不变深度预测为每个像素分配一个介于 0(近平面)和 1(远平面)之间的值,这两个平面均由模型在推理过程中确定。 |
| prs-eth/marigold-normals-v0-1 | 法线 | 表面法线预测值是屏幕空间相机坐标系下的单位长度 3D 向量,其取值范围为 -1 到 1。 |
| prs-eth/marigold-iid-appearance-v1-1 | 内置函数 | InteriorVerse 分解由 Albedo 以及两个 BRDF 材质属性组成:Roughness 和 Metallicity。 |
| prs-eth/marigold-iid-lighting-v1-1 | 内置函数 | HyperSim 对图像的分解 由反照率 $A$、漫反射着色 $S$ 和非漫反射残差 $R$ 组成:$I = A*S+R$。 |
请务必参阅调度器(Schedulers)指南,了解如何探索调度器速度与质量之间的权衡,并查看跨流水线复用组件部分,了解如何高效地将相同组件加载到多个流水线中。 此外,如需进一步了解如何降低此流水线的内存占用,请参阅此处的“减少内存占用”部分。
Marigold 流水线在设计时,调度器(scheduler)是嵌入在模型检查点中的。 不同调度器的最佳推理步数各不相同,不存在一个在所有情况下都表现最佳的通用值。 为了适应这一点,流水线
__call__方法中的num_inference_steps参数默认值为None(参见 API 参考)。 除非显式设置,否则该参数会从检查点配置文件(model_index.json)中的default_denoising_steps字段继承其值。 这确保了仅传入image参数调用流水线时,仍能获得高质量的预测结果。
以下示例主要基于深度预测,但同样适用于其他受支持的模态。 我们使用 Midjourney 生成的同一张爱因斯坦输入图像来展示预测结果。 这使得在不同模态和检查点之间比较预测结果的可视化变得更加容易。
深度预测
要获取深度预测,请将 prs-eth/marigold-depth-v1-1 检查点加载到 MarigoldDepthPipeline 中,将图像通过该流水线处理,并保存预测结果:
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() 函数应用 matplotlib 的 colormap(默认为 Spectral),将单通道 [0, 1] 深度范围内的预测像素值映射为 RGB 图像。
使用 Spectral colormap 时,深度较近的像素显示为红色,较远的像素显示为蓝色。
16 位 PNG 文件存储的是从 [0, 1] 范围线性映射到 [0, 65535] 的单通道值。
以下是原始预测和可视化后的预测。在可视化结果中,较暗且较近的区域(胡子)更容易被区分。
表面法线估计
将 prs-eth/marigold-normals-v1-1 检查点加载到 MarigoldNormalsPipeline 中,将图像通过该流水线处理,并保存预测结果:
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() 将三维预测值(像素值范围为 [-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”模型预测结果的示例代码:
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”模型预测结果的示例:
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() 函数。
以下是一些展示预测分解结果的示例。 所有模态都可以在 Intrinsic Image Decomposition Space 中查看。
加速推理
上述快速入门代码片段已针对质量和速度进行了优化:加载检查点,使用权重和计算的 fp16 变体,并执行默认数量(4 步)的去噪扩散步骤。
在牺牲预测质量的前提下,加速推理的第一步是将去噪扩散步骤减少到最少:
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 的轻量级替代方案,推理速度可提升 3 倍以上,
在 RTX 3090 上将调用时间缩短至 85ms。
请注意,使用轻量级 VAE 可能会略微降低预测的视觉质量。
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)到目前为止,我们已经优化了扩散步数和模型组件。自注意力操作占据了计算量的很大一部分。通过使用更高效的注意力处理器,可以加快其速度:
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)最后,如优化中所述,根据目标硬件的不同,启用torch.compile可以进一步提升性能。
然而,编译会在首次调用 pipeline 时产生显著的开销,因此只有在同一 pipeline 实例被反复调用(例如在循环中)时,启用编译才具有优势。
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。
推荐值因检查点而异,但主要取决于调度器类型。
集成机制的效果在表面法线预测中尤为明显:
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 的生成特性,每次预测都是唯一的,并由为潜在初始化采样的随机噪声所决定。 与传统的端到端密集回归网络相比,这成为一个明显的缺点,如下面的视频所示:
为了解决这个问题,可以向 pipeline 传递 latents 参数,该参数定义了扩散的起始点。
经验表明,将完全相同的起始点噪声 latent 与对应于上一帧预测的 latent 进行凸组合,可以得到足够平滑的结果,如下面的代码片段所示:
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,并计算其对下一帧潜在变量初始化的贡献。
现在的结果要稳定得多:
用于 ControlNet 的 Marigold
使用扩散模型进行深度预测的一个非常常见的应用场景是结合 ControlNet 使用。 深度的清晰度对于从 ControlNet 获得高质量结果至关重要。 如上所述与其他方法的对比所示,Marigold 在该任务上表现出色。 下面的代码片段演示了如何加载图像、计算深度,并以兼容的格式将其传入 ControlNet:
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")
定量评估
要在标准排行榜和基准测试(例如 NYU、KITTI 及其他数据集)中对 Marigold 进行定量评估,请遵循论文中概述的评估协议:加载全精度 fp32 模型,并为 num_inference_steps 和 ensemble_size 使用适当的值。
可选地,设置随机种子以确保可复现性。
最大化 batch_size 可实现最高的设备利用率。
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 字段中。
可以按如下方式对其进行可视化:
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
class diffusers.MarigoldDepthPipeline
< source >( unet: UNet2DConditionModelvae: AutoencoderKLscheduler: diffusers.schedulers.scheduling_ddim.DDIMScheduler | diffusers.schedulers.scheduling_lcm.LCMSchedulertext_encoder: CLIPTextModeltokenizer: CLIPTokenizerprediction_type: str | None = Nonescale_invariant: bool | None = Trueshift_invariant: bool | None = Truedefault_denoising_steps: int | None = Nonedefault_processing_resolution: int | None = None )
参数
- 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, 可选) — 使用给定模型生成合理质量预测所需的最少去噪扩散步数。此值必须在模型配置中设置。当调用 pipeline 时未显式设置num_inference_steps,将使用默认值。此设置是必需的,以确保与 pipeline 兼容的各种模型变体(例如依赖极短去噪调度的LCMScheduler和具有完整扩散调度的DDIMScheduler)都能产生合理的结果。 - default_processing_resolution (
int,可选) — 流水线中processing_resolution参数的推荐值。此值必须在模型配置中设置。当调用流水线时未显式设置processing_resolution,将使用默认值。这对于确保在使用以不同最佳处理分辨率值训练的各种模型变体时获得合理结果至关重要。
使用 Marigold 方法进行单目深度估计的 Pipeline:https://marigoldmonodepth.github.io。
该模型继承自 DiffusionPipeline。有关该库为所有流水线实现的通用方法(例如下载或保存、在特定设备上运行等),请参阅父类文档。
__call__
< source >( 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 = Noneensemble_size: int = 1processing_resolution: int | None = Nonematch_input_resolution: bool = Trueresample_method_input: str = 'bilinear'resample_method_output: str = 'bilinear'batch_size: int = 1ensembling_kwargs: dict[str, typing.Any] | None = Nonelatents: typing.Union[torch.Tensor, list[torch.Tensor], NoneType] = Nonegenerator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneoutput_type: str = 'np'output_uncertainty: bool = Falseoutput_latent: bool = Falsereturn_dict: bool = True ) → MarigoldDepthOutput or tuple
参数
- 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一致。
- reduction (
- 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 而不是普通元组。
返回值
MarigoldDepthOutput 或 tuple
如果 return_dict 为 True,则返回 MarigoldDepthOutput;否则返回一个 tuple,其中第一个元素是预测值,第二个元素是不确定性(或 None),第三个元素是潜在表示(或 None)。
调用 pipeline 时调用的函数。
示例:
>>> 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")class diffusers.pipelines.marigold.MarigoldDepthOutput
< source >( prediction: typing.Union[numpy.ndarray, torch.Tensor]uncertainty: typing.Union[NoneType, numpy.ndarray, torch.Tensor]latent: typing.Optional[torch.Tensor] )
参数
- 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
< source >( depth: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]val_min: float = 0.0val_max: float = 1.0color_map: str = 'Spectral' )
可视化深度图,例如 MarigoldDepthPipeline 的预测结果。
返回:list[PIL.Image.Image],包含深度图的可视化结果。
Marigold 法线估计 API
class diffusers.MarigoldNormalsPipeline
< source >( unet: UNet2DConditionModelvae: AutoencoderKLscheduler: diffusers.schedulers.scheduling_ddim.DDIMScheduler | diffusers.schedulers.scheduling_lcm.LCMSchedulertext_encoder: CLIPTextModeltokenizer: CLIPTokenizerprediction_type: str | None = Noneuse_full_z_range: bool | None = Truedefault_denoising_steps: int | None = Nonedefault_processing_resolution: int | None = None )
参数
- 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, 可选) — 使用给定模型生成合理质量预测所需的最少去噪扩散步数。此值必须在模型配置中设置。当调用 pipeline 时未显式设置num_inference_steps,将使用默认值。此设置是必需的,以确保与 pipeline 兼容的各种模型变体(例如依赖极短去噪调度的LCMScheduler和具有完整扩散调度的DDIMScheduler)都能产生合理的结果。 - default_processing_resolution (
int,可选) — 流水线中processing_resolution参数的推荐值。此值必须在模型配置中设置。当调用流水线时未显式设置processing_resolution,将使用默认值。这对于确保在使用以不同最佳处理分辨率值训练的各种模型变体时获得合理结果至关重要。
使用 Marigold 方法进行单目法线估计的 Pipeline:https://marigoldmonodepth.github.io。
该模型继承自 DiffusionPipeline。有关该库为所有流水线实现的通用方法(例如下载或保存、在特定设备上运行等),请参阅父类文档。
__call__
< source >( 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 = Noneensemble_size: int = 1processing_resolution: int | None = Nonematch_input_resolution: bool = Trueresample_method_input: str = 'bilinear'resample_method_output: str = 'bilinear'batch_size: int = 1ensembling_kwargs: dict[str, typing.Any] | None = Nonelatents: typing.Union[torch.Tensor, list[torch.Tensor], NoneType] = Nonegenerator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneoutput_type: str = 'np'output_uncertainty: bool = Falseoutput_latent: bool = Falsereturn_dict: bool = True ) → MarigoldNormalsOutput or tuple
参数
- 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"。
- reduction(
- 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 而不是普通元组。
返回值
MarigoldNormalsOutput 或 tuple
如果 return_dict 为 True,则返回 MarigoldNormalsOutput;否则返回一个 tuple,其中第一个元素是预测值,第二个元素是不确定性(或 None),第三个元素是潜在表示(或 None)。
调用 pipeline 时调用的函数。
示例:
>>> 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")class diffusers.pipelines.marigold.MarigoldNormalsOutput
< source >( prediction: typing.Union[numpy.ndarray, torch.Tensor]uncertainty: typing.Union[NoneType, numpy.ndarray, torch.Tensor]latent: typing.Optional[torch.Tensor] )
参数
- 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
< source >( normals: typing.Union[numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor]]flip_x: bool = Falseflip_y: bool = Falseflip_z: bool = False )
可视化表面法线,例如 MarigoldNormalsPipeline 的预测结果。
返回:list[PIL.Image.Image],包含表面法线可视化。
Marigold 本征图像分解 API
class diffusers.MarigoldIntrinsicsPipeline
< source >( unet: UNet2DConditionModelvae: AutoencoderKLscheduler: diffusers.schedulers.scheduling_ddim.DDIMScheduler | diffusers.schedulers.scheduling_lcm.LCMSchedulertext_encoder: CLIPTextModeltokenizer: CLIPTokenizerprediction_type: str | None = Nonetarget_properties: dict[str, typing.Any] | None = Nonedefault_denoising_steps: int | None = Nonedefault_processing_resolution: int | None = None )
参数
- 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, 可选) — 使用给定模型生成合理质量预测所需的最少去噪扩散步数。此值必须在模型配置中设置。当调用 pipeline 时未显式设置num_inference_steps,将使用默认值。此设置是必需的,以确保与 pipeline 兼容的各种模型变体(例如依赖极短去噪调度的LCMScheduler和具有完整扩散调度的DDIMScheduler)都能产生合理的结果。 - default_processing_resolution (
int,可选) — 流水线中processing_resolution参数的推荐值。此值必须在模型配置中设置。当调用流水线时未显式设置processing_resolution,将使用默认值。这对于确保在使用以不同最佳处理分辨率值训练的各种模型变体时获得合理结果至关重要。
使用 Marigold 方法进行本征图像分解(IID)的 Pipeline:https://marigoldcomputervision.github.io。
该模型继承自 DiffusionPipeline。有关该库为所有流水线实现的通用方法(例如下载或保存、在特定设备上运行等),请参阅父类文档。
__call__
< source >( 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 = Noneensemble_size: int = 1processing_resolution: int | None = Nonematch_input_resolution: bool = Trueresample_method_input: str = 'bilinear'resample_method_output: str = 'bilinear'batch_size: int = 1ensembling_kwargs: dict[str, typing.Any] | None = Nonelatents: typing.Union[torch.Tensor, list[torch.Tensor], NoneType] = Nonegenerator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneoutput_type: str = 'np'output_uncertainty: bool = Falseoutput_latent: bool = Falsereturn_dict: bool = True ) → MarigoldIntrinsicsOutput or tuple
参数
- 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"。
- reduction (
- 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 而不是普通元组。
返回值
MarigoldIntrinsicsOutput 或 tuple
如果 return_dict 为 True,则返回 MarigoldIntrinsicsOutput,否则返回一个 tuple,其中第一个元素是预测值,第二个元素是不确定性(或 None),第三个元素是潜在变量(或 None)。
调用 pipeline 时调用的函数。
示例:
>>> 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")>>> 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")class diffusers.pipelines.marigold.MarigoldIntrinsicsOutput
< source >( prediction: typing.Union[numpy.ndarray, torch.Tensor]uncertainty: typing.Union[NoneType, numpy.ndarray, torch.Tensor]latent: typing.Optional[torch.Tensor] )
参数
- 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
< source >( 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' )
参数
- 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,每个 target 和 sub-target 各对应一个。 - color_map (
str | dict[str, str],可选,默认为"Spectral") — 用于将单通道预测转换为彩色表示的色图。当传入字典时,可以为每种模态指定其专属的色图。
可视化内在图像分解,例如 MarigoldIntrinsicsPipeline 的预测结果。
返回:list[dict[str, PIL.Image.Image]],包含本征图像分解的可视化结果。