TExcelTAD

Preparing Image Data

An image dataset arrives as a folder of files plus a table or JSON file of labels (the layouts are in Image, Audio and Video Dataset Layouts). Before a model can learn from it, every file must decode, every label must match its file, every image must reach the same size and channel order, pixel values must be on the scale the model expects, boxes and masks must follow the image through every resize, and the split must keep near-identical photos on one side. This lesson does each step on arrays drawn in code, with OpenCV and NumPy, the same tools that run in the browser.

decodecheck, skip baduint8, H x W x 3 channelsBGR to RGBgray to 3 ch sizeresize + padmove the boxes scaledivide by 255float32, 0 to 1 standardisetraining mean/stdper channel augmentation (training only) goes between size and scale, or after

Verify files and labels

A training run that crashes on image 48,213 of 50,000, or silently trains on a black image, wastes hours. Decode every file once up front, record what fails, and compare the set of files with the set of labels in both directions.

python · try it yourself
import numpy as np
import cv2

rng = np.random.default_rng(0)
def png(img):
    ok, buf = cv2.imencode(".png", img)
    return buf.tobytes()

files = {
    "cat_01.png": png(rng.integers(0, 256, (40, 60, 3), dtype=np.uint8)),
    "cat_02.png": png(rng.integers(0, 256, (48, 48, 3), dtype=np.uint8)),
    "dog_01.png": png(rng.integers(0, 256, (30, 50), dtype=np.uint8)),          # grayscale
    "dog_02.png": b"<html>404 Not Found</html>",                               # an error page saved as .png
    "dog_03.png": png(np.zeros((40, 40, 3), dtype=np.uint8)),                  # all black
}
labels = {"cat_01.png": "cat", "cat_02.png": "cat", "dog_01.png": "dog",
          "dog_02.png": "dog", "dog_03.png": "dog", "dog_04.png": "dog"}

report = []
for name, data in files.items():
    img = cv2.imdecode(np.frombuffer(data, np.uint8), cv2.IMREAD_UNCHANGED)
    if img is None:
        report.append((name, "cannot decode"))
    elif img.ndim == 2:
        report.append((name, f"grayscale {img.shape}, convert to 3 channels"))
    elif img.std() < 1:
        report.append((name, "constant image, check the source"))
print("labels without a file:", sorted(set(labels) - set(files)))
print("files without a label:", sorted(set(files) - set(labels)))
for name, problem in report:
    print(f"{name}: {problem}")
labels without a file: ['dog_04.png']
files without a label: []
dog_01.png: grayscale (30, 50), convert to 3 channels
dog_02.png: cannot decode
dog_03.png: constant image, check the source

Five files, six labels, four problems: dog_04.png has a label but no file, dog_01.png decoded as a single-channel grayscale image, dog_02.png is not an image at all (a web server's error page saved under an image name, a classic of scraped datasets), and dog_03.png is a constant black image. cv2.imdecode returns None for undecodable bytes instead of raising, so the check must test for it.

Images with problems go into a quarantine list with the reason (the cleaning log idea), not silently dropped: a pattern in the failures (all from one camera, one date) is a finding.

Channels: BGR, RGB and grayscale

OpenCV decodes colour images in BGR order; PIL, scikit-image, Matplotlib and almost every pretrained model use RGB. Feeding BGR to a model trained on RGB swaps red and blue: the model still runs, and quietly gets worse. Convert once, at load time, with cv2.cvtColor(img, cv2.COLOR_BGR2RGB), and convert grayscale to three channels (cv2.COLOR_GRAY2RGB) if the model expects three. Images with an alpha channel (4 channels) need a decision too: drop it, or composite onto a background.

Resize or pad, and move the annotations

Models take a fixed input size. Stretching every image to a square distorts shapes; letterboxing keeps the aspect ratio by resizing the longer side and padding the rest. Every annotation must go through the same transform: class labels do not change, but boxes, masks and keypoints do.

Annotation Typical format What a resize does to it
class label one name or id per image nothing
bounding box Pascal VOC x_min, y_min, x_max, y_max in pixels; COCO x, y, w, h in pixels; YOLO cx, cy, w, h as fractions of the image scale and shift the coordinates
mask an array the size of the image (class id per pixel), or polygons resize with nearest-neighbour (never blend class ids)
keypoints (x, y, visibility) per point scale and shift like box corners
python · try it yourself
import numpy as np
import cv2

img = np.full((300, 500, 3), 200, dtype=np.uint8)            # H=300, W=500
cv2.rectangle(img, (100, 60), (220, 180), (0, 0, 255), -1)   # a red square (BGR)
box = np.array([100, 60, 220, 180], dtype=float)             # VOC: x_min, y_min, x_max, y_max
mask = np.zeros((300, 500), np.uint8); mask[60:181, 100:221] = 3   # class id 3

def letterbox(img, size, pad_value=114):
    h, w = img.shape[:2]
    s = size / max(h, w)
    nh, nw = round(h * s), round(w * s)
    top, left = (size - nh) // 2, (size - nw) // 2
    out = np.full((size, size) + img.shape[2:], pad_value, img.dtype)
    interp = cv2.INTER_NEAREST if img.ndim == 2 else cv2.INTER_AREA
    out[top:top + nh, left:left + nw] = cv2.resize(img, (nw, nh), interpolation=interp)
    return out, s, left, top

out, s, left, top = letterbox(img, 160)
new_box = box * s + np.array([left, top, left, top])
m, _, _, _ = letterbox(mask, 160, pad_value=0)
print("scale", round(s, 3), "| padding left/top", left, top, "| shape", out.shape)
print("box after:", np.round(new_box, 1).tolist())
cx, cy = (new_box[0] + new_box[2]) / 2 / 160, (new_box[1] + new_box[3]) / 2 / 160
w, h = (new_box[2] - new_box[0]) / 160, (new_box[3] - new_box[1]) / 160
print("as YOLO:", [round(float(v), 4) for v in (cx, cy, w, h)])
print("mask values after resize:", sorted(np.unique(m).tolist()))
rgb = cv2.cvtColor(out, cv2.COLOR_BGR2RGB)
r, c = int(round(new_box[1] + 5)), int(round(new_box[0] + 5))
print("pixel inside box, BGR:", out[r, c].tolist(), "RGB:", rgb[r, c].tolist())
scale 0.32 | padding left/top 0 32 | shape (160, 160, 3)
box after: [32.0, 51.2, 70.4, 89.6]
as YOLO: [0.32, 0.44, 0.24, 0.24]
mask values after resize: [0, 3]
pixel inside box, BGR: [0, 0, 255] RGB: [255, 0, 0]

The 500 x 300 image is scaled by 0.32 to 160 x 96 and padded by 32 rows at the top (and bottom). The box corners go through the same scale and shift and land at (32.0, 51.2) and (70.4, 89.6); in YOLO's normalised centre format that is [0.32, 0.44, 0.24, 0.24]. The mask, resized with nearest-neighbour, still contains only the ids 0 and 3. The last line shows the channel trap: the square was drawn as (0, 0, 255), which in OpenCV's BGR order is red; after conversion the same pixel reads [255, 0, 0] in RGB.

Normalise pixels with training statistics

Networks train best on inputs near zero with unit spread. The usual recipe: convert uint8 to float32, divide by 255, then subtract a per-channel mean and divide by a per-channel standard deviation. Fine-tuning a pretrained model? Use its statistics (for ImageNet models, mean [0.485, 0.456, 0.406] and std [0.229, 0.224, 0.225] in RGB). Training from scratch? Compute them on the training images only, exactly as a scaler is fitted on training rows. The split itself must respect who or what is in the photo: ten photos of the same person, or frames from the same camera, are near-duplicates, and spreading them over train and test inflates the score. Split by subject with a group splitter.

python · try it yourself
import numpy as np
from sklearn.model_selection import GroupShuffleSplit

rng = np.random.default_rng(1)
n_subjects, per_subject = 12, 5
subject = np.repeat(np.arange(n_subjects), per_subject)
tint = rng.uniform(0.7, 1.3, (n_subjects, 3))                 # each subject's lighting
images = np.clip(rng.normal(120, 40, (60, 16, 16, 3)) * tint[subject][:, None, None, :], 0, 255).astype(np.uint8)

split = GroupShuffleSplit(n_splits=1, test_size=0.25, random_state=0)
train_idx, test_idx = next(split.split(images, groups=subject))
print("train subjects:", sorted(set(subject[train_idx].tolist())))
print("test subjects: ", sorted(set(subject[test_idx].tolist())))

x_train = images[train_idx].astype(np.float32) / 255
mean = x_train.mean(axis=(0, 1, 2))
std = x_train.std(axis=(0, 1, 2))
print("training mean per channel:", [round(float(v), 3) for v in mean])
print("training std per channel: ", [round(float(v), 3) for v in std])
x_test = (images[test_idx].astype(np.float32) / 255 - mean) / std
print("test after standardising: mean", [round(float(v), 2) for v in x_test.mean(axis=(0, 1, 2))])
train subjects: [0, 1, 2, 3, 5, 7, 8, 9, 10]
test subjects:  [4, 6, 11]
training mean per channel: [0.477, 0.453, 0.487]
training std per channel:  [0.181, 0.173, 0.178]
test after standardising: mean [-0.18, 0.18, 0.17]

Subjects 4, 6 and 11 are held out completely, with all five of their images. The per-channel mean and standard deviation (about 0.48 and 0.18) come from the 45 training images only. Applied to the test images, the standardisation gives channel means of -0.18, 0.18 and 0.17 rather than exactly 0: the test subjects have their own lighting, and that small shift is the honest picture of what new subjects will look like.

Augmentation

Flips, crops, rotations, colour jitter, blur, noise, Cutout, MixUp and CutMix are in Image Augmentation. Two rules from this lesson apply to them: every geometric augmentation must move the boxes, masks and keypoints as well, and augmentation runs on training images only, on the fly, never on validation or test images.

Pitfalls

  • BGR fed to an RGB model: convert at load time and test it once on an image with a known colour.
  • Resizing masks with bilinear interpolation: creates class ids that do not exist; use nearest-neighbour.
  • Boxes not transformed with the image: the commonest silent bug in detection pipelines; draw a few boxes after preprocessing and look.
  • Normalisation statistics from all images: compute them on training images, or use the pretrained model's.
  • Random split of photos of the same subject, scene or camera: split by group.

Practice

  1. A 640 x 480 (W x H) image is letterboxed to 320 x 320. What are the scale factor and the padding, and where does a box with corners (64, 48) and (320, 240) end up?
Answer

Scale 320 / 640 = 0.5, so the image becomes 320 x 240, padded by (320 - 240) / 2 = 40 pixels at the top and bottom. The box becomes (32, 48 * 0.5 + 40) = (32, 64) to (160, 160).

  1. Your model reaches 97% validation accuracy on face photos but 70% on new users. The dataset has 20 photos per person and was split at random. What happened?
Answer

Photos of the same person sit in both training and validation, so the model is partly recognising people it has seen. Split with GroupShuffleSplit or GroupKFold by person to get an estimate that matches new users.

Test yourself

In which channel order does OpenCV's imdecode/imread return colour images?

  1. RGB
  2. BGR
  3. HSV
  4. RGBA always

Which interpolation should be used to resize a segmentation mask of class ids?

  1. Bilinear
  2. Bicubic
  3. Nearest-neighbour
  4. Area averaging

Where should the per-channel mean and std for normalisation come from when training from scratch?

  1. All images, including test
  2. The training images only
  3. The test images
  4. Always 0.5 and 0.5

The dataset has many photos per patient. How should it be split?

  1. Randomly by photo
  2. By patient, with a group splitter
  3. By file size
  4. By image brightness