Sub topic 9
Preparing a dataset in YOLO format
This chapter assumes you know basic Python, how bounding boxes are written in xyxy and normalized xywh form, and what a training and validation split is. By the end you will be able to lay out a dataset folder, write label files, write the dataset YAML, convert boxes from other formats, and check the result before training.
The folder layout
Ultralytics finds labels by path substitution. For each image path, it replaces the last /images/ directory component with /labels/ and changes the file extension to .txt. Your folders must follow this rule, or the trainer will treat images as unlabeled.
datasets/my_data/
images/
train/
img001.jpg
img002.jpg
val/
img101.jpg
labels/
train/
img001.txt
img002.txt
val/
img101.txtThe image images/train/img001.jpg is paired with labels/train/img001.txt. The file names must match exactly, apart from the extension.
The label file
Each label file holds one line per object. A line has five numbers separated by spaces: the class index, the box centre x and y, and the box width and height. All four box values are normalized, which means they are divided by the image width (for x and width) or the image height (for y and height). They fall between 0 and 1.
# labels/train/img001.txt (one line per object)
# class_id x_center y_center width height (all coordinates normalized to 0-1)
0 0.512 0.430 0.200 0.350
1 0.150 0.700 0.100 0.220In the real file, leave out the two comment lines. The label parser does not accept comments.
Several rules apply:
- Class indices start at 0 and have no gaps.
- An image with no objects either has no label file or has an empty one. Both count as background images. Such images are useful negatives, because they teach the model not to fire on empty scenes.
- Coordinates are relative, so resizing an image does not change its labels. Resizing with a changed aspect ratio, however, changes what the normalized box means in pixels. Keep the same boxes on the same content.
- Use a period as the decimal separator, with no commas or units.
The dataset YAML
The YAML file tells the trainer where the data is and what each class index means.
path: datasets/my_data
train: images/train
val: images/val
names:
0: cat
1: dogpath is the dataset root. train and val are relative to it. The names mapping must cover every class index used in your labels. A label line with class 2 in a two-class file produces an error, or the image is dropped with a warning.
Relative path values are resolved against Ultralytics' configured datasets directory, not always against your current folder. If the trainer reports that it cannot find the dataset, use an absolute path to remove the doubt.
Converting boxes from pixel formats
Annotation tools often export pixel corners (xyxy) or COCO style [x, y, width, height], where x and y are the top-left corner. You must convert these to normalized centre format. The function below handles both input styles.
def to_yolo(box, img_w, img_h, fmt="xyxy"):
# Returns (x_center, y_center, width, height), each in 0-1.
if fmt == "xyxy":
x1, y1, x2, y2 = box
elif fmt == "coco":
x, y, w, h = box
x1, y1, x2, y2 = x, y, x + w, y + h
else:
raise ValueError(f"unknown format: {fmt}")
# Clip to the image so a box never extends outside it.
x1, x2 = max(0, x1), min(img_w, x2)
y1, y2 = max(0, y1), min(img_h, y2)
xc = (x1 + x2) / 2 / img_w
yc = (y1 + y2) / 2 / img_h
w = (x2 - x1) / img_w
h = (y2 - y1) / img_h
return xc, yc, w, h
def write_label(path, objects, img_w, img_h, fmt="xyxy"):
# objects is a list of (class_id, box) pairs.
with open(path, "w") as f:
for cls_id, box in objects:
xc, yc, w, h = to_yolo(box, img_w, img_h, fmt)
if w <= 0 or h <= 0:
continue # skip degenerate boxes
f.write(f"{cls_id} {xc:.6f} {yc:.6f} {w:.6f} {h:.6f}\n")
print(to_yolo((100, 50, 300, 250), 640, 480))
# (0.3125, 0.3125, 0.3125, 0.4166666666666667)The box (100, 50, 300, 250) in a 640 by 480 image has its centre at pixel (200, 150). Dividing gives 0.3125 for both values. Its width of 200 pixels is 0.3125 of the image width, and its height of 200 pixels is about 0.417 of the image height.
The most common conversion error is dividing x values by the image height, or the reverse. Confirm which is which by drawing a converted box back onto the image, as shown later in this chapter.
Check one more point. Some tools store image dimensions before applying an EXIF rotation. A phone photo can display rotated while its stored pixel array is not. If your boxes appear turned by 90 degrees, apply the EXIF orientation when you read the image size, or re-save the images with the rotation applied.
Splitting the data
A validation set measures how the model does on images it has not trained on. Use these guidelines:
- Hold out about 10 to 20 percent of the images for validation. Smaller datasets may need the higher share to get a stable metric.
- Split by source, not by image, when images come from the same video, scene or session. Consecutive video frames look nearly identical. If some land in train and others in val, the validation score will look better than real-world performance.
- Keep class proportions similar in both splits. A rare class that appears only in train cannot be evaluated.
- Do not tune on your final test data. If you want an unbiased final number, keep a third
testsplit and only use it once.
The diagram shows the flow from raw annotations to a trainable dataset.
Checking the dataset before training
Errors in labels cost hours of training time, and they rarely produce an error message. A model trained on shifted boxes will train without complaint and score badly. A quick script catches the common faults.
from pathlib import Path
def check_labels(root, split, num_classes):
root = Path(root)
img_dir = root / "images" / split
lbl_dir = root / "labels" / split
image_exts = {".jpg", ".jpeg", ".png", ".bmp"}
problems = []
counts = [0] * num_classes
for img in sorted(img_dir.iterdir()):
if img.suffix.lower() not in image_exts:
continue
lbl = lbl_dir / (img.stem + ".txt")
if not lbl.exists():
problems.append(f"{img.name}: no label file (background image)")
continue
for n, line in enumerate(lbl.read_text().splitlines(), 1):
parts = line.split()
if len(parts) != 5:
problems.append(f"{lbl.name}:{n}: expected 5 values, got {len(parts)}")
continue
cls_id = int(float(parts[0]))
xc, yc, w, h = map(float, parts[1:])
if not 0 <= cls_id < num_classes:
problems.append(f"{lbl.name}:{n}: class {cls_id} out of range")
continue
counts[cls_id] += 1
if not all(0 <= v <= 1 for v in (xc, yc, w, h)):
problems.append(f"{lbl.name}:{n}: value outside 0-1")
elif w == 0 or h == 0:
problems.append(f"{lbl.name}:{n}: zero-size box")
print("instances per class:", counts)
for p in problems:
print(p)
return problems
check_labels("datasets/my_data", "train", num_classes=2)The script reports files without labels, lines with the wrong number of values, class indices out of range, values outside 0 to 1, and zero-size boxes. It also prints the instance count for each class, which shows imbalance. A class with 30 instances next to one with 3000 will usually get a low AP.
Numbers are not enough. Draw boxes on a sample of images and look at them.
import cv2
def draw_labels(img_path, lbl_path, names, out_path):
img = cv2.imread(str(img_path))
h, w = img.shape[:2]
for line in open(lbl_path).read().splitlines():
cls_id, xc, yc, bw, bh = line.split()
xc, bw = float(xc) * w, float(bw) * w
yc, bh = float(yc) * h, float(bh) * h
p1 = (int(xc - bw / 2), int(yc - bh / 2))
p2 = (int(xc + bw / 2), int(yc + bh / 2))
cv2.rectangle(img, p1, p2, (0, 255, 0), 2)
cv2.putText(img, names[int(cls_id)], (p1[0], max(p1[1] - 5, 12)),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
cv2.imwrite(out_path, img)
draw_labels("datasets/my_data/images/train/img001.jpg",
"datasets/my_data/labels/train/img001.txt",
{0: "cat", 1: "dog"}, "check_img001.jpg")This script needs opencv-python. Open the output and confirm each box sits on its object with the right name.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Log says "0 labels found" or all images are "background" | `images`/`labels` folder names do not match the path rule, or file stems differ | Rename folders; match stems exactly |
| Images reported as corrupt | Class index outside `names`, or a value above 1 | Run the check script; clip or fix values |
| Boxes land in the wrong place at training time | x and y swapped, or width divided by height | Draw boxes and compare with the image |
| Boxes are rotated 90 degrees | EXIF orientation ignored | Apply the rotation, then re-export |
| Validation mAP is very high but real use is poor | Near-duplicate frames in both splits | Re-split by source |
| One class never detected | Few instances, or labels use another index | Check the per-class counts and the `names` map |
Annotation quality
Consistent labels matter more than a large number of them. Decide your rules before labeling and apply them to every image:
- Draw each box tight around the visible part of the object.
- Label every instance of a target class, including small, partly hidden and cut-off ones. If you skip some, the model learns that those objects are background.
- Choose how to treat crowds and heavy occlusion, and then follow that rule everywhere.
- Do not use two classes for things a human cannot reliably tell apart in the image.
Exercise
An image is 800 pixels wide and 600 pixels tall. A dog is boxed with pixel corners (200, 150, 600, 450) and the class index of dog is 1. Write the label line, and name two things that could cause the trainer to ignore this image.
Show answer
The centre is x = (200 + 600) / 2 = 400 and y = (150 + 450) / 2 = 300. Normalized, xcenter = 400 / 800 = 0.5 and ycenter = 300 / 600 = 0.5. Width is 400 / 800 = 0.5 and height is 300 / 600 = 0.5. The line is "1 0.5 0.5 0.5 0.5". The image could be ignored or flagged corrupt if its label file is in the wrong folder or has a different stem, so the trainer finds no labels, or if a line has a class index outside the names mapping or a coordinate above 1.
Exercise
You extracted 5000 frames from 10 videos and randomly assigned 80 percent to train and 20 percent to val. Validation mAP is 0.95, but the model does poorly on new videos. What went wrong, and how do you fix the split?
Show answer
Neighbouring frames from one video are nearly identical, so many val frames have close twins in train. The model has effectively seen the validation images, which inflates mAP. Split by video: for example, put 8 videos in train and 2 in val, so no video appears in both. Then retrain and compare the new val score.