Datasets documentation

处理图像数据

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v4.8.4).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

处理图像数据

本指南介绍了处理图像数据集的具体方法。学习如何:

有关如何处理任意类型数据集的指南,请参阅通用处理指南。

映射

map() 函数可以针对整个数据集应用转换。

例如,创建一个基本的 Resize 函数:

>>> def transforms(examples):
...     examples["pixel_values"] = [image.convert("RGB").resize((100,100)) for image in examples["image"]]
...     return examples

现在使用 map() 函数调整整个数据集的大小,并设置 batched=True 以通过接受示例批次来加速处理。该转换返回 pixel_values 作为可缓存的 PIL.Image 对象:

>>> dataset = dataset.map(transforms, remove_columns=["image"], batched=True)
>>> dataset[0]
{'label': 6,
 'pixel_values': <PIL.PngImagePlugin.PngImageFile image mode=RGB size=100x100 at 0x7F058237BB10>}

缓存文件可以节省时间,因为您无需对同一转换执行两次。map() 函数最适合用于每次训练仅运行一次的操作(例如调整图像大小),而不是用于每个 epoch 都会执行的操作(例如数据增强)。

map() 会占用一定的内存,但你可以通过以下参数来降低其内存需求:

  • batch_size 决定了每次调用 transform 函数时处理的样本数量。
  • writer_batch_size 决定了在存储之前,内存中保留的已处理示例数量。

这两个参数的默认值均为 1000,如果您正在存储图像,这可能会带来较高的开销。在使用 map() 时,请降低这些值以减少内存占用。

应用转换

🤗 Datasets 可将任何库或包中的数据增强应用于您的数据集。可以使用 set_transform() 对数据批次即时应用转换,从而减少磁盘空间占用。

以下示例使用了 torchvision,但您也可以自由使用其他数据增强库,例如 Albumentations、Kornia 和 imgaug。

例如,如果您想随机更改图像的颜色属性:

>>> from torchvision.transforms import Compose, ColorJitter, ToTensor

>>> jitter = Compose(
...     [
...          ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.7),
...          ToTensor(),
...     ]
... )

创建一个函数以应用ColorJitter变换:

>>> def transforms(examples):
...     examples["pixel_values"] = [jitter(image.convert("RGB")) for image in examples["image"]]
...     return examples

使用 set_transform() 函数应用转换:

>>> dataset.set_transform(transforms)
Update on GitHub