在 GitHub 上编辑

Live.log_image()

将给定的图像 val 保存到输出文件 name 中。

def log_image(name: str, val):

用法

from dvclive import Live

with Live(cache_images=True) as live:
    # 1. Log an image from a numpy array:
    import numpy as np
    img_numpy = np.ones((500, 500), np.uint8) * 255
    live.log_image("numpy.png", img_numpy)

    # 2. Or log a matplotlib figure:
    from matplotlib import pyplot as plt
    fig, ax = plt.subplots()
    ax.plot([1, 2, 3, 4])
    live.log_image("matplotlib.png", fig)

    # 3. Or log a `PIL.image`:
    from PIL import Image
    img_pil = Image.new("RGB", (500, 500), (250, 250, 250))
    live.log_image("pil.png", img_pil)

    # 4. Or log an existing image:
    live.log_image("sample.png", "run/batch_0_sample.png")

描述

val 支持的值包括:

  • 有效的 NumPy 数组(可通过 PIL.Image.fromarray 转换为图像)
  • 一个 matplotlib.figure.Figure 实例
  • 一个 PIL.Image 实例
  • 图像文件的路径(strPath),其格式需能被 PIL.Image.open() 读取

图像将被保存至 {Live.plots_dir}/images/{name}。当使用 Live(cache_images=True) 时,图像目录也会在 Live.end() 中被缓存。此时,会生成一个 .dvc 文件以跟踪该目录,并将目录添加到 .gitignore 文件中,以防止 Git 跟踪:

dvclive
└── plots
    ├── .gitignore
    ├── images
    │   ├── numpy.png
    │   ├── matplotlib.png
    │   ├── pil.png
    │   └── sample.png
    └── images.dvc

可通过 dvc plots 可视化已记录的图像:

$ dvc plots diff dvclive/plots

每步的图像

默认情况下,每次步骤中图像都会被覆盖。但你可以使用以下模式记录图像:live.log_image(f"folder/{live.step}.png", img)

import numpy as np
from dvclive import Live

with Live() as live:
    base_img = np.ones((500, 500), np.uint8)
    for i in range(10):
      live.log_image(
        f"numpy/{live.step}.png", base_img * i * 10)
      live.next_step()

在 DVC Studio 和 VSCode 的 DVC 扩展 中,符合此模式的文件夹将通过图像滑块进行渲染:

DVCLive Studio Image Slider

DVCLive VSCode Image Slider

参数

  • name - 此命令输出的图像文件名。

  • val - 要保存的图像。支持的值列表请参见 描述

异常

  • dvclive.error.InvalidDataTypeError - 当提供的 val 类型不受支持时抛出。
内容

🐛 发现问题?告诉我们!或者修复它:

在 GitHub 上编辑

有疑问?加入我们的聊天,我们会为您提供帮助:

Discord 聊天