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

创建图像数据集

创建和共享图像数据集有两种方法。本指南将向您展示如何:

  • Create an image dataset from local files in python with Dataset.push_to_hub(). This is an easy way that requires only a few steps in python.

  • 使用 ImageFolder 创建一个包含一些元数据的图像数据集。这是一种无需编写代码的解决方案,可快速创建包含数千张图像的数据集。

您可以通过要求用户先共享其联系信息来控制对数据集的访问权限。有关如何在 Hub 上启用此功能的更多信息,请参阅 Gated datasets 指南。

ImageFolder

ImageFolder 是一个数据集构建器,旨在快速加载包含数千张图片的图像数据集,且无需编写任何代码。

💡 查看 Split 模式层级,了解 ImageFolder 如何根据数据集仓库结构创建数据集划分。

ImageFolder 会根据目录名称自动推断数据集的类别标签。请将数据集存储为如下目录结构:

folder/train/dog/golden_retriever.png
folder/train/dog/german_shepherd.png
folder/train/dog/chihuahua.png

folder/train/cat/maine_coon.png
folder/train/cat/bengal.png
folder/train/cat/birman.png

如果数据集遵循 ImageFolder 结构,则可以直接使用 load_dataset() 加载:

>>> from datasets import load_dataset

>>> dataset = load_dataset("path/to/folder")

这相当于在 load_dataset() 中手动传入 imagefolder 以及 data_dir 中的目录:

>>> dataset = load_dataset("imagefolder", data_dir="/path/to/folder")

您还可以使用 imagefolder 来加载包含多个拆分的数据集。为此,您的数据集目录应具有以下结构:

folder/train/dog/golden_retriever.png
folder/train/cat/maine_coon.png
folder/test/dog/german_shepherd.png
folder/test/cat/bengal.png

如果所有图像文件都位于同一个目录中,或者它们不在同一层级的目录结构中,则不会自动添加label列。如果需要该列,请显式设置drop_labels=False。

如果您希望为数据集添加额外信息,例如文本说明或边界框,请在您的文件夹中将其添加为 metadata.csv 文件。这可以让您快速创建用于不同计算机视觉任务的数据集,例如文本说明或目标检测。您也可以使用 JSONL 文件 metadata.jsonl 或 Parquet 文件 metadata.parquet。

folder/train/metadata.csv
folder/train/0001.png
folder/train/0002.png
folder/train/0003.png

您也可以将图像打包为 zip 文件,在这种情况下,每个 zip 文件都应同时包含图像和元数据

folder/train.zip
folder/test.zip
folder/validation.zip

您的 metadata.csv 文件必须包含一个 file_name 或 *_file_name 字段,用于将图像文件与其元数据关联起来:

file_name,additional_feature
0001.png,This is a first value of a text feature you added to your images
0002.png,This is a second value of a text feature you added to your images
0003.png,This is a third value of a text feature you added to your images

或使用 metadata.jsonl:

{"file_name": "0001.png", "additional_feature": "This is a first value of a text feature you added to your images"}
{"file_name": "0002.png", "additional_feature": "This is a second value of a text feature you added to your images"}
{"file_name": "0003.png", "additional_feature": "This is a third value of a text feature you added to your images"}

此处 file_name 必须是位于元数据文件旁边的图像文件的名称。更一般地,它必须是包含元数据的目录到图像文件的相对路径。

在数据集中的每一行中,可以指向多于一张图像,例如当输入和输出都是图像时:

{"input_file_name": "0001.png", "output_file_name": "0001_output.png"}
{"input_file_name": "0002.png", "output_file_name": "0002_output.png"}
{"input_file_name": "0003.png", "output_file_name": "0003_output.png"}

您还可以定义图像列表。在这种情况下,您需要将该字段命名为 file_names 或 *_file_names。示例如下:

{"frames_file_names": ["0001_t0.png", "0001_t1.png"], label: "moving_up"}
{"frames_file_names": ["0002_t0.png", "0002_t1.png"], label: "moving_down"}
{"frames_file_names": ["0003_t0.png", "0003_t1.png"], label: "moving_right"}

图像描述

图像描述数据集包含描述图像的文字。metadata.csv 示例可能如下所示:

file_name,text
0001.png,This is a golden retriever playing with a ball
0002.png,A german shepherd
0003.png,One chihuahua

使用 ImageFolder 加载数据集,它将创建一个 text 列用于存储图像说明:

>>> dataset = load_dataset("imagefolder", data_dir="/path/to/folder", split="train")
>>> dataset[0]["text"]
"This is a golden retriever playing with a ball"

目标检测

目标检测数据集包含边界框和类别,用于识别图像中的对象。metadata.jsonl 示例可能如下所示:

{"file_name": "0001.png", "objects": {"bbox": [[302.0, 109.0, 73.0, 52.0]], "categories": [0]}}
{"file_name": "0002.png", "objects": {"bbox": [[810.0, 100.0, 57.0, 28.0]], "categories": [1]}}
{"file_name": "0003.png", "objects": {"bbox": [[160.0, 31.0, 248.0, 616.0], [741.0, 68.0, 202.0, 401.0]], "categories": [2, 2]}}

使用 ImageFolder 加载数据集,它将创建一个包含边界框和类别的 objects 列:

>>> dataset = load_dataset("imagefolder", data_dir="/path/to/folder", split="train")
>>> dataset[0]["objects"]
{"bbox": [[302.0, 109.0, 73.0, 52.0]], "categories": [0]}

将数据集上传到 Hub

创建数据集后,您可以使用 push_to_hub() 方法将其共享到 Hub。请确保已安装 huggingface_hub 库,并已登录您的 Hugging Face 账户(更多详情请参阅 使用 Python 上传教程)。

使用 push_to_hub() 上传您的数据集:

>>> from datasets import load_dataset

>>> dataset = load_dataset("imagefolder", data_dir="/path/to/folder", split="train")
>>> dataset.push_to_hub("stevhliu/my-image-captioning-dataset")

WebDataset

WebDataset 格式基于 TAR 归档,适用于大型图像数据集。 实际上,您可以将图像分组到 TAR 归档中(例如,每个 TAR 归档包含 1GB 的图像),并拥有数千个 TAR 归档:

folder/train/00000.tar
folder/train/00001.tar
folder/train/00002.tar
...

在归档中,每个示例由共享相同前缀的文件组成:

e39871fd9fd74f55.jpg
e39871fd9fd74f55.json
f18b91585c4d3f3e.jpg
f18b91585c4d3f3e.json
ede6e66b2fb59aab.jpg
ede6e66b2fb59aab.json
ed600d57fcee4f94.jpg
ed600d57fcee4f94.json
...

您可以使用 JSON 或文本文件来存放图像标签/说明/边界框。

加载您的 WebDataset,它会为每个文件后缀(此处为“jpg”和“json”)创建一个列:

>>> from datasets import load_dataset

>>> dataset = load_dataset("webdataset", data_dir="/path/to/folder", split="train")
>>> dataset[0]["json"]
{"bbox": [[302.0, 109.0, 73.0, 52.0]], "categories": [0]}

也可以像这样在每个示例中包含多张图片:

e39871fd9fd74f55.input.jpg
e39871fd9fd74f55.output.jpg
e39871fd9fd74f55.json
f18b91585c4d3f3e.input.jpg
f18b91585c4d3f3e.output.jpg
f18b91585c4d3f3e.json
...

有关 WebDataset 格式和 python 库的更多详细信息,请参阅 WebDataset 文档。

Lance

Lance 是一种开放的多模态数据湖仓表格式。Lance 表不仅可以原生存储文本和标量值,还可以与您的表格数据一起存储大型二进制对象(blob),例如图像、音频和视频。

从磁盘上的图像文件及其关联元数据(例如,说明文字和尺寸)出发,您可以将一个自包含的 Lance 数据集写入本地的 *.lance 目录。生成的表可以在 image 列中存储编码后的图像字节,同时保留您的元数据列。

例如,你可以从类似以下元数据开始:

{'caption': 'Cordelia and Dudley on their wedding  day last year', 'height': 315, 'width': 233}
{'caption': 'Statistics on challenges for automation in 2021', 'height': 299, 'width': 701}

您可以为元数据和图像字节定义一个 pyarrow schema,构建一个表,并将其写入为 Lance 数据集:

import lance
import pyarrow as pa

schema = pa.schema(
    [
        pa.field("caption", pa.utf8()),
        pa.field("height", pa.int32()),
        pa.field("width", pa.int32()),
        # ... add any additional metadata columns you want here ...
        pa.field("image", pa.binary()),
    ]
)

# Provide image files alongside metadata
rows = [
    {
        "image_path": "/path/to/images/0001.jpg",
        "caption": "Cordelia and Dudley on their wedding  day last year",
        "height": 315,
        "width": 233,
    },
    {
        "image_path": "/path/to/images/0002.jpg",
        "caption": "Statistics on challenges for automation in 2021",
        "height": 299,
        "width": 701,
    },
]

image_bytes = []
for r in rows:
    with open(r["image_path"], "rb") as f:
        image_bytes.append(f.read())

table = pa.table(
    {
        "caption": [r["caption"] for r in rows],
        "height": [r["height"] for r in rows],
        "width": [r["width"] for r in rows],
        "image": image_bytes,
    },
    schema=schema,
)

ds = lance.write_dataset(
    table,
    "./images.lance",
    schema=schema,
    mode="create",
)

以下是存储图像的 Lance 表的典型视图(image 列包含编码后的字节):

+-----------------------------------------------+--------+-------+-----+------------------------------+
| caption                                       | height | width | ... | image                        |
+-----------------------------------------------+--------+-------+-----+------------------------------+
| "Cordelia and Dudley on their wedding ..."    | 315    | 233   | ... | b"\\xff\\xd8\\xff...\\xd9"   |
| "Statistics on challenges for automation ..." | 299    | 701   | ... | b"\\xff\\xd8\\xff...\\xd9"   |
+-----------------------------------------------+--------+-------+-----+------------------------------+

使用这种方法,你可以在 Lance 中存储任意大小的图像数据集。生成的 images.lance/ 目录及其 *.lance 文件可以像上述其他示例一样上传到 Hugging Face Hub。请参阅 lance-format/laion-1m on the Hub 数据集,了解 Lance 图像数据集的示例。

有关使用 Lance 数据集的更多详细信息,请参阅 Lance 文档。

Update on GitHub