Computer Vision Dataset Preparation: From Annotation to a Checked Export
Computer vision dataset preparation is finished when you can answer one question with evidence: do the labels still refer to the same pixels after every resize, flip, crop, format change and split? A file that parses is not proof. A box can be perfectly valid YOLO or COCO and still sit 100 pixels away from its object.
This article follows one box through the common coordinate systems and transforms, builds a small synthetic dataset whose true boxes can be read back from the pixels, breaks it on purpose, and ends with the checks to run before training.
The lifecycle, and where labels get damaged
A dataset lifecycle with a check at each hand over
Eight stages in order: define and collect, annotate, review, split, preprocess, augment the training part, export and validate, each with what it receives and what it passes on.
| stage | input | output | what happens |
|---|---|---|---|
| 1. Define and collect | task and conditions | images and a label taxonomy | Decide classes, extent rules and which cameras, sites and conditions must be covered. |
| 2. Annotate | images, written rules | labels with provenance | Record who or what made each label. |
| 3. Review | labels | accepted labels | Second annotator or audit sample; look for misses. |
| 4. Split | accepted labels, group ids | train, validation, test | Assign whole groups, before any copies are made. |
| 5. Preprocess | all splits | uniform images and labels | Same steps everywhere, including at inference. |
| 6. Augment training data | training split only | extra variants | Each geometric change must update its labels. |
| 7. Export | splits | COCO, YOLO or other files | Check class numbering and coordinate convention. |
| 8. Validate | exported files | pass or a list of faults | Read the files back as the trainer will. |
Stage 1 of 8, Define and collect. Input: task and conditions. Output: images and a label taxonomy.
Taxonomy and collection come first
Three decisions are expensive to change later:
- Classes. Write a one-sentence definition per class, what to do with borderline items, and whether "other" exists.
- Extent. Box the visible part or the estimated whole object? Include shadows, handles, reflections?
- Coverage. Collect the lighting, viewpoints, devices and backgrounds you expect in use, and record them as metadata. Include images with no target objects, marked as deliberately empty, so that a model sees what not to report.
If a model pre-labels the images, reviewing and correcting its proposals needs its own rules and measurements.
One box, three descriptions
Take an 800 by 450 image with a box whose top-left corner is (120, 90), width 200 and height 100, so its corners are (120, 90) and (320, 190). Coordinates are continuous, with the origin at the top-left and y pointing down.
| Format | Stores | For this box |
|---|---|---|
| Corners | x1, y1, x2, y2 in pixels |
120, 90, 320, 190 |
| COCO | [x, y, width, height] in pixels, one JSON file for many images |
[120, 90, 200, 100], area 20000 |
| YOLO (Ultralytics) | class cx cy w h, centre and size divided by image width or height, one text file per image |
0 0.275000 0.311111 0.250000 0.222222 |
| Pascal VOC | xmin, ymin, xmax, ymax in pixels, one XML file per image |
120, 90, 320, 190 in a zero-based tool |
| Image classification | No box: a class per image, as folders or a CSV | Not applicable |
The arithmetic behind the YOLO line, for image size W by H:
cx = (x1 + x2) / 2 / W = 220 / 800 = 0.275cy = (y1 + y2) / 2 / H = 140 / 450 = 0.311111w = (x2 − x1) / W = 0.25,h = (y2 − y1) / H = 0.222222
Three traps hide in that table. Class numbering: YOLO class indices start at 0, while COCO category ids are whatever the categories list says and conventionally start at 1, so an off-by-one silently renames every object. Pixel numbering: the original Pascal VOC development kit counts the top-left pixel as (1, 1), so a reader and writer with different assumptions shift boxes by one pixel. Which image the numbers refer to: a photo with an EXIF orientation tag may be displayed rotated; if the annotation tool applied the tag and the training loader did not (or the reverse), the boxes refer to a differently turned picture, and for quarter turns width and height are swapped. Ultralytics documents that its coordinates refer to the image as displayed, with EXIF orientation applied. Normalise orientation once, early.
The worked box in corner, COCO and YOLO form
A rectangle in an 800 by 450 image written as corner pixels, as a COCO top left corner with width and height, and as a normalised YOLO line.
| format | values |
|---|---|
| corner pixelstop left and bottom right corner | x1 = 120, y1 = 90, x2 = 320, y2 = 190 |
| COCO xywh[x_min, y_min, x2 − x1, y2 − y1] | [120, 90, 200, 100] |
| YOLO normalisedclass, (x1 + x2)/2W, (y1 + y2)/2H, (x2 − x1)/W, (y2 − y1)/H | 0 0.275000 0.311111 0.250000 0.222222 |
The box lies inside the image.
From corner pixels input: corners 120, 90, 320, 190; COCO [120, 90, 200, 100]; YOLO 0 0.275000 0.311111 0.250000 0.222222. The box lies inside the image.
Converting between formats without renaming classes
The coordinate arithmetic is the easy half of a conversion. The bookkeeping is where datasets are silently corrupted.
- Map category ids explicitly. COCO ids need not be contiguous: the 80 categories of the original dataset use ids from 1 to 90, with gaps. Writing
class = category_id - 1into YOLO files then produces indices that point at the wrong names, or past the end. Build a table from thecategorieslist, for instanceindex = {c["id"]: i for i, c in enumerate(sorted(coco["categories"], key=lambda c: c["id"]))}, and write the class names out in that order. - Say what happens to shapes. Going from polygons to detection boxes keeps only each polygon's tight box. An object split by an occluder can have several polygons in COCO; a converter that keeps the first loses part of it.
- Handle
iscrowd. COCO marks groups of objects that were not separated, stored as run-length masks. A format without that flag cannot express "ignore this region", so decide whether to drop or keep them, and record the choice. - Keep empty images. An image with no annotations appears in COCO's
imageslist and nowhere else; a converter that iterates over annotations forgets it. In YOLO, Ultralytics treats a missing or empty label file as a background image, which also means a lost label file goes unnoticed. - Round once. Converting back and forth with integer rounding drifts. Keep one master in pixel coordinates and generate every export from it.
Resizing: stretch and letterbox are not interchangeable
Models usually need a fixed input size. Two common ways to get from W × H to W' × H':
- Stretch. Scale each axis separately:
sx = W'/W,sy = H'/H, thenx' = sx·x,y' = sy·y. Normalised coordinates do not change, but shapes are distorted. - Letterbox. Scale both axes by
r = min(W'/W, H'/H), then pad what is left:x' = r·x + pad_x,y' = r·y + pad_y. Shapes are preserved, and normalised coordinates do change, because the canvas now includes padding.
For the worked box and a 640 by 640 input, stretching gives sx = 0.8 and sy = 640/450. Letterboxing gives r = 0.8, a 640 by 360 resized image and 140 pixels of padding above and below.
The code blocks below need NumPy and Pillow. Their outputs were produced with Python 3.13.12, NumPy 2.5.4 and Pillow 13.0.0, and every image and label in them is synthetic.
def to_coco(box): # corners -> [x, y, width, height] in pixels
x1, y1, x2, y2 = box
return [x1, y1, x2 - x1, y2 - y1]
def to_yolo(box, W, H): # corners -> centre and size, divided by the image size
x1, y1, x2, y2 = box
return ((x1 + x2) / 2 / W, (y1 + y2) / 2 / H, (x2 - x1) / W, (y2 - y1) / H)
def from_yolo(values, W, H):
cx, cy, w, h = values
return ((cx - w / 2) * W, (cy - h / 2) * H, (cx + w / 2) * W, (cy + h / 2) * H)
def stretch(box, size, new):
sx, sy = new[0] / size[0], new[1] / size[1]
return (box[0] * sx, box[1] * sy, box[2] * sx, box[3] * sy)
def letterbox_params(size, new):
r = min(new[0] / size[0], new[1] / size[1])
resized = (round(size[0] * r), round(size[1] * r))
pad = ((new[0] - resized[0]) // 2, (new[1] - resized[1]) // 2)
return r, resized, pad
def letterbox(box, size, new):
r, _, (px, py) = letterbox_params(size, new)
return (box[0] * r + px, box[1] * r + py, box[2] * r + px, box[3] * r + py)
box, size, new = (120, 90, 320, 190), (800, 450), (640, 640)
print("COCO bbox", to_coco(box), " area", to_coco(box)[2] * to_coco(box)[3])
for name, moved, canvas in (("original", box, size), ("stretched", stretch(box, size, new), new),
("letterboxed", letterbox(box, size, new), new)):
print(f"{name:12s} corners {tuple(round(v, 1) for v in moved)} YOLO 0 "
+ " ".join(f"{v:.6f}" for v in to_yolo(moved, *canvas)))
COCO bbox [120, 90, 200, 100] area 20000
original corners (120, 90, 320, 190) YOLO 0 0.275000 0.311111 0.250000 0.222222
stretched corners (96.0, 128.0, 256.0, 270.2) YOLO 0 0.275000 0.311111 0.250000 0.222222
letterboxed corners (96.0, 212.0, 256.0, 292.0) YOLO 0 0.275000 0.393750 0.250000 0.125000
Now suppose images are letterboxed but the label code assumes a stretch, which amounts to leaving the normalised numbers alone. Nothing crashes. The labels are simply wrong:
A stretch label placed on a letterboxed image
On a square 640 pixel canvas, the correct box sits lower and flatter than the stale box, which starts higher and is much taller; their intersection over union is about 0.36.
A: correct label (solid)B: stale stretch label (dashed)intersection
| quantity | value |
|---|---|
| area of correct label(x2 − x1)(y2 − y1) | 12800 |
| area of stale stretch label(x2 − x1)(y2 − y1) | 22755.52 |
| intersectionoverlap width × overlap height | 9315.52 |
| unionarea A + area B − intersection | 26240 |
| IoUintersection / union | 0.3550 |
| Dice2 × intersection / (area A + area B) | 0.5240 |
This IoU is below the threshold 0.5 (a match needs IoU at or above it).
Intersection 9315.52, union 26240: IoU 0.3550, Dice 0.5240.
| Preprocessing step | Changes labels? | Check |
|---|---|---|
| Apply EXIF orientation | Yes, if labels were made on the unrotated pixels | Width and height as the annotator saw them |
| Stretch resize | Pixel values yes, normalised no | Distortion acceptable? |
| Letterbox or padding | Both | Offsets applied to labels |
| Crop or tiling | Both, with clipping | Rule for partly visible objects; keep tile origins |
| Grayscale, contrast | No | Does any class depend on colour? |
| Re-encoding (for example to JPEG) | No | Small objects and thin defects still visible |
Cropping and tiling: decide what "visible enough" means
A crop moves the origin and cuts objects. For a crop window, intersect each box with it, subtract the window's top-left corner, and measure the share that survived:
visible = area(box ∩ window) / area(box)
Cropping the worked image to x from 200 to 800 leaves the box spanning 200 to 320: visible = 120 / 200 = 0.6, and the new label is (0, 90, 120, 190). Keep a box only above a chosen share, and remember the consequence: a dropped box whose pixels are still in the crop teaches the model that those pixels are background. With tiling, overlap neighbouring tiles by at least the size of the objects you care about, keep each tile's origin so predictions can be mapped back, and put all tiles of one image in the same split.
A round-trip test with a pixel reference
Unit tests that compare converters with each other can all agree on the same mistake. A stronger test uses data where the truth is in the pixels: draw solid coloured rectangles, export their labels, read the files back, transform images and labels, and then recover each box from the colour and compare.
The first block creates six "sessions", each one fixed scene filmed three times with a two pixel drift, which will matter for splitting, and writes both YOLO text files and a COCO JSON file.
import json
import tempfile
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw
CLASSES = ["red_block", "blue_block"]
COLORS = [(220, 30, 30), (30, 60, 220)]
W, H = 800, 450
root = Path(tempfile.mkdtemp())
rng = np.random.default_rng(0)
dataset = [] # (file name, session, [(class, box), ...])
for session in range(6): # one session = one fixed scene, filmed three times
scene = []
for cls in range(2):
if cls == 1 and session % 3 == 2: # some sessions have no blue block
continue
x, y = int(rng.integers(20, 300)) + 380 * cls, int(rng.integers(20, 300))
scene.append((cls, (x, y, x + int(rng.integers(60, 100)), y + int(rng.integers(50, 120)))))
for frame in range(3):
noise = rng.integers(110, 150, (H, W, 1)).repeat(3, axis=2).astype(np.uint8)
image = Image.fromarray(noise)
draw = ImageDraw.Draw(image)
boxes = [(cls, (x1 + 2 * frame, y1, x2 + 2 * frame, y2)) for cls, (x1, y1, x2, y2) in scene]
for cls, (x1, y1, x2, y2) in boxes:
draw.rectangle([x1, y1, x2 - 1, y2 - 1], fill=COLORS[cls]) # PIL includes both ends
name = f"s{session}_f{frame}"
image.save(root / f"{name}.png")
dataset.append((name, session, boxes))
coco = {"images": [], "annotations": [], "categories": [{"id": i + 1, "name": n} for i, n in enumerate(CLASSES)]}
for image_id, (name, _, boxes) in enumerate(dataset, 1):
(root / f"{name}.txt").write_text("".join(
f"{cls} " + " ".join(f"{v:.6f}" for v in to_yolo(b, W, H)) + "\n" for cls, b in boxes))
coco["images"].append({"id": image_id, "file_name": f"{name}.png", "width": W, "height": H})
for cls, b in boxes:
bbox = to_coco(b)
coco["annotations"].append({"id": len(coco["annotations"]) + 1, "image_id": image_id,
"category_id": cls + 1, "bbox": bbox, "area": bbox[2] * bbox[3], "iscrowd": 0})
(root / "coco.json").write_text(json.dumps(coco))
print(len(dataset), "images,", len(coco["annotations"]), "boxes")
18 images, 30 boxes
The second block is the test. The tolerance of one pixel allows for interpolation at edges.
def box_from_pixels(image, cls):
"""Tight box of the pixels that have the class colour: the ground truth the label must match."""
rgb = np.asarray(image, dtype=float)
ys, xs = np.nonzero(np.linalg.norm(rgb - COLORS[cls], axis=2) < 90)
return (xs.min(), ys.min(), xs.max() + 1, ys.max() + 1)
def worst_edge_error(a, b):
return max(abs(p - q) for p, q in zip(a, b))
def read_yolo(name, canvas):
rows = [line.split() for line in (root / f"{name}.txt").read_text().splitlines()]
return [(int(r[0]), from_yolo([float(v) for v in r[1:]], *canvas)) for r in rows]
def read_coco(name):
data = json.loads((root / "coco.json").read_text())
image_id = next(i["id"] for i in data["images"] if i["file_name"] == f"{name}.png")
return [(a["category_id"] - 1, (a["bbox"][0], a["bbox"][1], a["bbox"][0] + a["bbox"][2], a["bbox"][1] + a["bbox"][3]))
for a in data["annotations"] if a["image_id"] == image_id]
def letterbox_image(image, new):
_, resized, pad = letterbox_params(image.size, new)
canvas = Image.new("RGB", new, (114, 114, 114))
canvas.paste(image.resize(resized, Image.BILINEAR), pad)
return canvas
worst = {"YOLO read back": 0, "COCO read back": 0, "stretch": 0, "letterbox": 0,
"horizontal flip": 0, "letterbox image, stretched labels": 0}
new = (640, 640)
for name, _, _ in dataset:
image = Image.open(root / f"{name}.png")
for (cls, from_txt), (_, from_json) in zip(read_yolo(name, image.size), read_coco(name)):
x1, y1, x2, y2 = from_txt
cases = {
"YOLO read back": (image, from_txt),
"COCO read back": (image, from_json),
"stretch": (image.resize(new, Image.BILINEAR), stretch(from_txt, image.size, new)),
"letterbox": (letterbox_image(image, new), letterbox(from_txt, image.size, new)),
"horizontal flip": (image.transpose(Image.FLIP_LEFT_RIGHT), (W - x2, y1, W - x1, y2)),
"letterbox image, stretched labels": (letterbox_image(image, new), stretch(from_txt, image.size, new)),
}
for case, (pixels, label) in cases.items():
worst[case] = max(worst[case], worst_edge_error(label, box_from_pixels(pixels, cls)))
for case, error in worst.items():
print(f"{case:34s} worst edge error {error:6.2f} px {'ok' if error <= 1.0 else 'FAIL'}")
YOLO read back worst edge error 0.00 px ok
COCO read back worst edge error 0.00 px ok
stretch worst edge error 0.67 px ok
letterbox worst edge error 0.60 px ok
horizontal flip worst edge error 0.00 px ok
letterbox image, stretched labels worst edge error 120.91 px FAIL
The last row shows that the test can fail. A test that has never been seen to fail tells you little. Adapt the idea to your own pipeline by pushing a few synthetic images with known shapes through the real loading and augmentation code, not a copy of it.
Augmentation: which changes keep labels true
An augmentation is label-preserving only for your task. A horizontal flip is harmless for pebbles and wrong for text, digits, or classes such as "left glove". A hue shift destroys a class defined by colour.
| Operation | Label update | Risk |
|---|---|---|
| Horizontal or vertical flip | x1' = W − x2, x2' = W − x1 (same for y) |
Left and right semantics, text, gravity |
| Translate, scale | Shift or scale coordinates, then clip | Objects pushed out of frame |
| Crop | Intersect with the crop, drop boxes with little left | Labels on a few visible pixels |
| Rotation, shear | Transform the shape, then take a new box | Box grows if only corners are transformed |
| Brightness, contrast, hue | None | Colour-defined or faint-defect classes |
| Blur, noise, cutout | None | Small objects erased but still labelled |
| Mosaic, MixUp | Combine labels of several images | Unnatural context; check that the trainer applies them correctly |
Rotation deserves a number. If you only have a box, the usual update is the box around its four rotated corners. For a rounded object that box is much larger than the object itself:
import math
canvas = Image.new("L", (400, 300), 0)
ImageDraw.Draw(canvas).ellipse([100, 100, 299, 199], fill=255) # object box (100, 100, 300, 200)
angle = 30
turned = np.asarray(canvas.rotate(angle, resample=Image.NEAREST, center=(200, 150)))
ys, xs = np.nonzero(turned)
tight = (int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1)
cos, sin = math.cos(math.radians(angle)), math.sin(math.radians(angle))
corners = [(200 + dx * cos + dy * sin, 150 - dx * sin + dy * cos) # image y axis points down
for dx in (-100, 100) for dy in (-50, 50)]
loose = (min(x for x, _ in corners), min(y for _, y in corners),
max(x for x, _ in corners), max(y for _, y in corners))
def iou(a, b):
w = max(0, min(a[2], b[2]) - max(a[0], b[0]))
h = max(0, min(a[3], b[3]) - max(a[1], b[1]))
return w * h / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - w * h)
print("tight box from rotated pixels ", tight)
print("box around rotated corners ", tuple(round(v, 1) for v in loose))
print(f"IoU between them {iou(tight, loose):.3f}")
tight box from rotated pixels (110, 83, 290, 217)
box around rotated corners (88.4, 56.7, 311.6, 243.3)
IoU between them 0.579
A label broken by rotating only the box corners
A smaller tight box sits entirely inside a much larger box built from rotated corners; their intersection over union is about 0.58.
A: tight box of object (solid)B: box of rotated corners (dashed)intersection
| quantity | value |
|---|---|
| area of tight box of object(x2 − x1)(y2 − y1) | 24120 |
| area of box of rotated corners(x2 − x1)(y2 − y1) | 41649.12 |
| intersectionoverlap width × overlap height | 24120 |
| unionarea A + area B − intersection | 41649.12 |
| IoUintersection / union | 0.5791 |
| Dice2 × intersection / (area A + area B) | 0.7335 |
Intersection 24120, union 41649.12: IoU 0.5791, Dice 0.7335.
Keep rotation angles small when labels are boxes, or rotate polygons or masks and recompute the box. Apply random augmentation only to the training split, after splitting, so that no variant of a test image is ever trained on.
Splitting without leakage
A split has a training part for fitting, a validation part for choosing settings and a test part used once for the final estimate. With n items and target shares such as 0.8, 0.1, 0.1, check the achieved shares per split and per class: the share of class c in a split is p_c = n_c / (sum of all class counts in that split).
- Random assignment by image is right only if images are independent.
- Stratified assignment keeps class shares similar. It does nothing about related images.
- Group-aware assignment keeps every image of a group (video clip, patient, part, site, session) on one side. Use it whenever images share a source.
Leakage means information from evaluation data reaching training. Consecutive video frames, burst photos, tiles of one large image and augmented copies are the usual routes, and they inflate scores without any error message. It happens in well-known data too: Barz and Denzler found near-duplicates of CIFAR test images in the training sets.
A random split puts near copies on both sides
Training holds two frames of session A and one of session B, while the test set holds another frame of A and another of B. Arrows link each near copy across the boundary between training and test.
| box | boundary | arrows to |
|---|---|---|
| Session A, frame 1 | Train | — |
| Session A, frame 2 | Train | Session A, frame 3 (twin) |
| Session B, frame 1 | Train | Session B, frame 2 (twin) |
| Session A, frame 3 | Test | — |
| Session B, frame 2 | Test | — |
5 boxes and 2 arrows. No box is selected.
Checking for identical files is not enough, as the synthetic sessions show:
import hashlib
def report(assignment):
sessions = {split: {s for n, s, _ in dataset if assignment[n] == split} for split in ("train", "val", "test")}
hashes = {split: {hashlib.sha256((root / f"{n}.png").read_bytes()).hexdigest()
for n, _, _ in dataset if assignment[n] == split} for split in sessions}
leaked = sum(1 for n, s, _ in dataset if assignment[n] == "test" and s in sessions["train"])
tested = sum(1 for n, _, _ in dataset if assignment[n] == "test")
print(f" identical files shared by train and test: {len(hashes['train'] & hashes['test'])}")
print(f" test images whose session is also in train: {leaked} of {tested}")
for split in sessions:
counts = [sum(c == i for n, _, boxes in dataset if assignment[n] == split for c, _ in boxes) for i in range(2)]
print(f" {split:5s} boxes per class {counts} share of {CLASSES[0]} {counts[0] / max(1, sum(counts)):.2f}")
names = [n for n, _, _ in dataset]
order = np.random.default_rng(1).permutation(len(names))
print("random split by image (12 / 3 / 3)")
report({names[i]: "train" if k < 12 else "val" if k < 15 else "test" for k, i in enumerate(order)})
print("split by session (4 / 1 / 1 sessions)")
report({n: {4: "val", 5: "test"}.get(s, "train") for n, s, _ in dataset})
random split by image (12 / 3 / 3)
identical files shared by train and test: 0
test images whose session is also in train: 3 of 3
train boxes per class [12, 8] share of red_block 0.60
val boxes per class [3, 3] share of red_block 0.50
test boxes per class [3, 1] share of red_block 0.75
split by session (4 / 1 / 1 sessions)
identical files shared by train and test: 0
test images whose session is also in train: 0 of 3
train boxes per class [12, 9] share of red_block 0.57
val boxes per class [3, 3] share of red_block 0.50
test boxes per class [3, 0] share of red_block 1.00
The hash check reports zero in both cases, although in the random split every test image has a near twin in training. The group split fixes that and reveals a different problem: with only six groups, the test set ended up with no blue block at all. Grouping and balance pull against each other. Choose the groups first, then look at class counts, and collect more groups if a class vanishes. Libraries offer ready-made tools, for example scikit-learn's GroupShuffleSplit. For how leakage and group constraints appear in graph-structured data, see masks, splits and leakage.
Validate the exported files
| Check | Why |
|---|---|
| Every image has a label file or is declared empty | Missing files look like negatives |
| Class indices within range, names in the intended order | Off-by-one renames classes |
| Boxes have positive size and lie inside the image | Wrong units or stale transforms |
COCO image_id and category_id references resolve; ids unique |
Silent drops |
COCO area matches the geometry |
COCO's small, medium and large metrics use it |
| Image size in the file equals the real size | EXIF or resize mismatch |
| No group appears in two splits; no near duplicates across splits | Leakage |
| Overlay a random sample and look at it | Catches what rules cannot |
About area: COCO evaluation counts an object as small below 32² pixels and large above 96², measured on the segmentation. An export that writes box area for a polygon can move objects between those bands.
A line-level check catches basic YOLO faults:
def check_yolo_line(line, n_classes):
fields = line.split()
if len(fields) != 5:
return "not five fields"
cls, (cx, cy, w, h) = int(fields[0]), map(float, fields[1:])
if not 0 <= cls < n_classes:
return "unknown class index"
if w <= 0 or h <= 0:
return "empty box"
if min(cx - w / 2, cy - h / 2) < -1e-6 or max(cx + w / 2, cy + h / 2) > 1 + 1e-6:
return "box leaves the image (or pixels were written instead of fractions)"
return "ok"
for line in ["0 0.275000 0.311111 0.250000 0.222222",
"2 0.5 0.5 0.1 0.1",
"0 220 140 200 100",
"0 0.95 0.5 0.2 0.1",
"1 0.5 0.5 0.0 0.1"]:
print(f"{line:40s} {check_yolo_line(line, len(CLASSES))}")
0 0.275000 0.311111 0.250000 0.222222 ok
2 0.5 0.5 0.1 0.1 unknown class index
0 220 140 200 100 box leaves the image (or pixels were written instead of fractions)
0 0.95 0.5 0.2 0.1 box leaves the image (or pixels were written instead of fractions)
1 0.5 0.5 0.0 0.1 empty box
It cannot tell a wrong box from a right one: the stale letterbox label above would pass. Only a pixel reference or a human look can.
Ready for training, evaluation and use
Before training, freeze a dataset version: images, labels, split lists, class names, preprocessing settings and the code that applied them. Evaluate on the untouched test split, per class and per condition, not only as one average. At deployment, apply exactly the same orientation, resize and normalisation as in training, and map model outputs back through the inverse transform (for letterbox, subtract the padding and divide by r). Then keep collecting the cases the model gets wrong, as a new version rather than an edit of the old one.
Anastig as one worked environment
Disclosure: the author of this article is also involved in building Anastig.
Anastig is an independent, early-access visual AI platform, not part of TGraphX; the Anastig overview on this site explains how its Studio and Vision Lab differ. Status as shown on its Studio page on 2026-11-27:
| Module | Status | Access |
|---|---|---|
| Annotation Studio | Available | Demo without an account |
| Export Center | Available | Current image in the demo; dataset ZIP when signed in |
| Dataset Manager | Beta | Signed in |
| Preprocessing | Beta | Signed in |
| Augmentation | Beta | Signed in |
| Training, Deployment, Evaluation, Workflows | Coming soon | Not available |
The signed-in features were not exercised for this article, and the pricing page does not say which plan includes them. What follows is based on the published application on that date. The public module pages and roadmap describe preprocessing and augmentation as an exported configuration, so check what your own export contains.
- Storage. The demo keeps images in your browser. A signed-in workspace uploads and stores images, labels and versions server-side, with images in Anastig's managed storage or an S3-compatible bucket.
- Splits. Dataset versions are split randomly or stratified by class, from a seed. There is no group-aware split. The health check flags byte-identical files across splits, which, as shown above, does not catch near copies. Keep related images together by other means.
- Preprocessing at export. EXIF auto-orientation, resize, grayscale, contrast boost, skipping unreadable files and clipping or dropping out-of-bounds labels, with labels updated for geometric steps. The resize is a stretch; no letterbox, padding or tiling is applied.
- Augmentation at export. Flips, rotation, scale, translate, shear, box-safe crop, colour changes, blur, noise, cutout and random erasing, seeded, and by default not applied to validation or test. Mosaic and MixUp are not offered.
- Export. A ZIP in YOLO detection or segmentation, COCO, Pascal VOC or Anastig JSON, with an integrity check that blocks the download if it fails. Existing YOLO and COCO annotations can be imported.
- Demo export. Labels for the current image only, without splits or augmentation. Which formats appear depends on the task; Pascal VOC holds boxes only. The demo's
dataset.yamlcontains placeholder paths to edit. If you export COCO from polygons, check theareafield before using size-based metrics.
Whatever tool writes your files, run your own checks on them. The scripts above work from files, not from any particular product; Anastig keeps a short formats page.
To find more instances of a rare object while annotating, see visual similarity search from one example, including why its matches need review.
Whether images leave your machine when a model helps with labelling depends on where it runs: see browser, WebGPU or GPU worker.
References
- Lin et al., Microsoft COCO: Common Objects in Context, 2014; data format and detection evaluation.
- Ultralytics, Object detection dataset format.
- Everingham et al., The Pascal Visual Object Classes (VOC) Challenge, 2010.
- Pascal VOC 2012, development kit documentation.
- Barz and Denzler, Do We Train on Test Data? Purging CIFAR of Near-Duplicates, 2019.
- Kapoor and Narayanan, Leakage and the reproducibility crisis in machine-learning-based science, 2023.
- Pillow, ImageOps module, including
exif_transpose.