Image, Audio and Video Dataset Layouts
Tables fit in one file. Media datasets do not: ten thousand photos are ten thousand files, and the labels have to live somewhere next to them. Over the years a few layouts have become conventions, and most tools (PyTorch's ImageFolder, Hugging Face datasets, Ultralytics YOLO, Keras) expect one of them. Knowing them lets you load a dataset in one line, and check it for the mistakes that layouts invite.
Image classification: one folder per class
The simplest layout encodes the label in the folder name, with the split (train, validation, test) one level above:
flowers/
├── train/
│ ├── daisy/ 0001.jpg 0002.jpg ...
│ ├── rose/ 0101.jpg ...
│ └── tulip/ ...
├── val/
│ ├── daisy/ rose/ tulip/
└── test/
├── daisy/ rose/ tulip/It needs no label file at all, which is its strength and its weakness: moving a file moves its label, and a file dropped in the wrong folder is silently mislabelled. The alternative is a flat folder of images plus a label file (file,label per line), the usual choice for multi-label data and for anything with more than one annotation per image.
Here we build a small dataset in this layout from scikit-learn's handwritten digits (8 × 8 greyscale images), then inspect it the way you would inspect a real one:
import os
import tempfile
import numpy as np
from PIL import Image
from sklearn.datasets import load_digits
digits = load_digits()
root = tempfile.mkdtemp()
rng = np.random.default_rng(0)
for i in range(60): # 60 images of the digits 0, 1 and 2
label = digits.target[i]
if label > 2:
continue
split = "test" if rng.random() < 0.25 else "train"
folder = os.path.join(root, split, f"digit_{label}")
os.makedirs(folder, exist_ok=True)
pixels = (digits.images[i] * 16).clip(0, 255).astype(np.uint8) # 0..16 -> 0..255
Image.fromarray(pixels).save(os.path.join(folder, f"{i:04}.png"))
for split in ["train", "test"]:
counts = {c: len(os.listdir(os.path.join(root, split, c)))
for c in sorted(os.listdir(os.path.join(root, split)))}
print(split, counts)
sample = Image.open(os.path.join(root, "train", "digit_0", "0000.png"))
print("one file:", sample.size, sample.mode)train {'digit_0': 6, 'digit_1': 5, 'digit_2': 4}
test {'digit_0': 2, 'digit_1': 1, 'digit_2': 3}
one file: (8, 8) L
Counting files per class and split is the first check on any image dataset: it shows the class balance and catches empty or misnamed folders (Daisy/ next to daisy/).
Checks that layouts need
Two problems are specific to folders of files: the same image in two places (a duplicate across train and test makes the test score too optimistic) and files that are not what they claim (corrupt, truncated or zero-byte files, or a .jpg that is really a PNG). Hashing the file contents finds exact duplicates; opening every file finds broken ones:
import hashlib
import io
import os
import shutil
import tempfile
import numpy as np
from PIL import Image
root = tempfile.mkdtemp()
rng = np.random.default_rng(1)
for split, cls, name in [("train", "cat", "a.png"), ("train", "cat", "b.png"), ("train", "dog", "c.png"),
("test", "dog", "d.png")]:
os.makedirs(os.path.join(root, split, cls), exist_ok=True)
img = rng.integers(0, 256, (16, 16, 3), dtype=np.uint8)
Image.fromarray(img).save(os.path.join(root, split, cls, name))
# Problems a real dataset might have:
shutil.copy(os.path.join(root, "train", "cat", "a.png"), os.path.join(root, "test", "dog", "e.png"))
with open(os.path.join(root, "train", "dog", "f.png"), "wb") as fh:
fh.write(b"\x89PNG not really")
seen = {}
for folder, _, files in sorted(os.walk(root)):
for f in sorted(files):
path = os.path.join(folder, f)
rel = os.path.relpath(path, root)
data = open(path, "rb").read()
digest = hashlib.sha256(data).hexdigest()[:12]
try:
Image.open(io.BytesIO(data)).verify()
status = "ok"
except Exception:
status = "BROKEN"
dup = f" duplicate of {seen[digest]}" if digest in seen else ""
seen.setdefault(digest, rel)
print(f"{rel:18} {digest} {status}{dup}")test/dog/d.png eddf13c6377f ok
test/dog/e.png 759dfa659a6c ok
train/cat/a.png 759dfa659a6c ok duplicate of test/dog/e.png
train/cat/b.png 134aa2cd4913 ok
train/dog/c.png 7fb320cb60bb ok
train/dog/f.png a8626d27cb13 BROKEN
test/dog/e.png is a byte-for-byte copy of train/cat/a.png: a leak between the splits and a label conflict (cat in one place, dog in the other). f.png is not an image at all. Near-duplicates (the same photo resized or recompressed) have different hashes; finding them needs perceptual hashes or embeddings, covered in Duplicate Detection.
Object detection and segmentation layouts
| Format | Images | Annotations |
|---|---|---|
| COCO | one folder per split | one JSON file per split with images, annotations, categories (boxes as x, y, w, h in pixels) |
| Pascal VOC | JPEGImages/ |
one XML file per image (boxes as corners) |
| YOLO | images/train/… |
labels/train/<same name>.txt, one line class x_center y_center w h per object, normalised to 0–1 |
| segmentation masks | images/ |
masks/ with a PNG per image, each pixel's value is its class id |
The YOLO convention in code: a box in pixels becomes a line of normalised centre coordinates.
def to_yolo(box, img_w, img_h, cls):
x, y, w, h = box # COCO: top-left corner, width, height
xc, yc = (x + w / 2) / img_w, (y + h / 2) / img_h
return f"{cls} {xc:.4f} {yc:.4f} {w / img_w:.4f} {h / img_h:.4f}"
print(to_yolo([100, 120, 60, 180], 640, 480, 0)) # the person from the COCO example
print(to_yolo([90, 220, 140, 90], 640, 480, 1)) # the bicycle0 0.2031 0.4375 0.0938 0.3750
1 0.2500 0.5521 0.2188 0.1875
Audio datasets
Audio datasets are usually a folder of files plus a metadata table (file, transcript or label, speaker, duration, sample rate). The file format matters:
| Format | Compression | Use |
|---|---|---|
| WAV (PCM) | none | the safe default for training data; simple to read |
| FLAC | lossless, about half the size of WAV | archives and large speech corpora |
| MP3, AAC, Opus | lossy | listening; compression artefacts can confuse models and differ from what the model sees in production |
The size of uncompressed audio follows directly from its parameters, which is a useful sanity check on a dataset's total size:
def wav_mb(seconds, rate, bits, channels):
return seconds * rate * (bits // 8) * channels / 1e6
print(f"1 h speech, 16 kHz, 16-bit, mono: {wav_mb(3600, 16_000, 16, 1):7.1f} MB")
print(f"1 h music, 44.1 kHz, 16-bit, stereo: {wav_mb(3600, 44_100, 16, 2):7.1f} MB")
print(f"1,000 h of the speech above: {wav_mb(3600 * 1000, 16_000, 16, 1) / 1000:7.1f} GB")1 h speech, 16 kHz, 16-bit, mono: 115.2 MB
1 h music, 44.1 kHz, 16-bit, stereo: 635.0 MB
1,000 h of the speech above: 115.2 GB
Keep the sample rate, bit depth and channel count the same across a dataset (or record them in the metadata and convert on loading): a mix of 8 kHz phone calls and 48 kHz studio recordings lets a model learn the recording setup instead of the content.
Video datasets
Video comes in a container (MP4, MKV, WebM) holding streams encoded with a codec (H.264, H.265, VP9, AV1). Datasets either keep whole clips plus a label per clip (action recognition), or extract frames to images at a fixed rate and annotate frames (detection and tracking, with an object id that links boxes across frames). Typical metadata: clip id, start and end time, fps, resolution, and the source video, so that clips from the same video never end up in both train and test.
Pitfalls
- Label by location: a misplaced file is a mislabelled file. Count files per folder and spot-check.
- Leaks across splits: the same image, the same speaker, or clips from the same video in train and test. Split by source, then check with hashes.
- Coordinate conventions: COCO pixels with corner and size, VOC corners, YOLO normalised centres.
- Hidden format mix: different resolutions, colour modes (RGB, greyscale, RGBA with transparency), sample rates or fps in one dataset.
Practice
- A YOLO label line reads
2 0.5 0.5 0.25 0.5for a 640 × 480 image. What is the box in COCO pixels?
Answer
Width 0.25 × 640 = 160, height 0.5 × 480 = 240, centre (320, 240), so the top-left corner is (320 − 80, 240 − 120) = (240, 120): [240, 120, 160, 240], class 2.
- A speech dataset is split randomly by file into train and test, and the test accuracy is excellent. What leak should you check first?
Answer
The same speakers in both splits. The model may recognise voices it has heard before rather than generalise. Split by speaker id.
Test yourself
In the one-folder-per-class layout, where is an image's label stored?
- In the file's metadata
- In a separate CSV file
- In the name of the folder that contains it
- In the pixel values
What does a SHA-256 hash of file contents find?
- Near-duplicate images that were resized
- Exact byte-for-byte duplicates
- Blurry images
- Wrong labels
YOLO label files store boxes as…
- Pixel corners
- Pixel top-left corner, width and height
- Class and centre, width, height normalised to 0-1
- Polygons
Why is WAV or FLAC usually preferred over MP3 for training data?
- MP3 cannot store speech
- They are lossless, so no compression artefacts are baked into the data
- They are smaller
- Models cannot read MP3