QuiddityML

Common image data bugs in PyTorch (BGR, rotated photos, uint8 vs float)

Five families of image pipeline bugs (shape, number, color, geometry and file) with a runnable PyTorch example for each, and a four-step check that catches many of them before you touch the model.

Computer VisionBy · 29 November 2026 · 11 min read

An image data bug is a mistake in how images are loaded, converted or labeled before the model sees them. The model code can be correct and still learn the wrong thing, because the tensors it receives differ from the ones you think it receives. Some of these bugs raise an error on the first batch. The harder ones run without an error, and the image often still looks fine on screen. The same few come up again and again, so knowing them by name makes them faster to find.

Shape bugs

An image tensor in PyTorch usually has the shape (batch, channels, height, width), such as (8, 3, 224, 224) for 8 color images of 224 by 224 pixels. Shape bugs put the right numbers in the wrong layout:

  • width and height swapped
  • a missing batch dimension
  • an unexpected alpha channel, the fourth channel that stores transparency
  • channels-last data, shaped (height, width, channels), fed to code that expects channels first

Shape bugs: width and height swapped, missing batch dimension, unexpected alpha channel, channels-last data fed to channels-first code. Number bugs: wrong dtype or range, normalization applied twice or not at all, integer overflow.

Some shape bugs raise an error, and those are the easy ones. A convolution layer built for 3 input channels checks the second dimension of its input:

import torch
from torch import nn

conv = nn.Conv2d(3, 8, kernel_size=3)   # expects (batch, 3, H, W)
hwc = torch.rand(1, 224, 224, 3)        # channels-last, as most loaders return it
try:
    conv(hwc)
except RuntimeError as e:
    print("channels-last:", str(e)[:120])

rgba = torch.rand(1, 4, 224, 224)       # a PNG with an alpha channel
try:
    conv(rgba)
except RuntimeError as e:
    print("alpha:", str(e)[:120])
# channels-last: Given groups=1, weight of size [8, 3, 3, 3], expected input[1, 224, 224, 3] to have 3 channels, but got 224 channels ins
# alpha: Given groups=1, weight of size [8, 3, 3, 3], expected input[1, 4, 224, 224] to have 3 channels, but got 4 channels inste

"got 224 channels" means the layer read the height as the channel count, so the tensor is channels-last. "got 4 channels" means an alpha channel came along from a PNG file. Calling .convert("RGB") when opening the file drops it.

The worse shape bugs run. A common one is fixing a channels-last tensor with reshape instead of permute. Both give the shape (3, H, W), but only permute moves the values to the right places:

import torch

# a 2 by 3 RGB image, channels last: pixel (row, col) holds [R, G, B]
hwc = torch.tensor([[[10, 11, 12], [20, 21, 22], [30, 31, 32]],
                    [[40, 41, 42], [50, 51, 52], [60, 61, 62]]])

right = hwc.permute(2, 0, 1)   # moves the channel axis to the front
wrong = hwc.reshape(3, 2, 3)   # same shape, values poured in reading order

print("red channel, permute:", right[0].tolist())
print("red channel, reshape:", wrong[0].tolist())
# red channel, permute: [[10, 20, 30], [40, 50, 60]]
# red channel, reshape: [[10, 11, 12], [20, 21, 22]]

The red values in this image end in 0, so the correct red channel is [[10, 20, 30], [40, 50, 60]]. After reshape the "red channel" holds a mix of red, green and blue from the first two pixels. No error is raised, the shape is right and the model trains on scrambled pixels.

Width and height get swapped for a similar reason: libraries disagree on the order. Pillow reports an image's size as (width, height) and its resize takes (width, height). A PyTorch tensor is (channels, height, width), and torch.nn.functional.interpolate takes size=(height, width). Passing the same pair to both gives two different images.

Number bugs

Number bugs give the model the right shape with the wrong values:

  • the wrong dtype (the type of each number, such as uint8 for whole numbers from 0 to 255 or float32 for decimals) or the wrong range
  • normalization applied twice or not at all
  • integer overflow

A decoded image usually arrives as uint8 from 0 to 255. Many models expect float32 decimals from 0 to 1. Others expect standardized values: each channel has a fixed mean subtracted and is divided by a fixed spread called the standard deviation. The code below sends one small image through four versions of that conversion:

import torch
from torch import nn

mean = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1)   # ImageNet values
std = torch.tensor([0.229, 0.224, 0.225]).view(3, 1, 1)

def normalize(x):
    return (x - mean) / std

# a 2 by 2 image decoded as uint8, values 0 to 255
x = torch.tensor([[[30, 220], [128, 255]],
                  [[25, 210], [128, 0]],
                  [[20, 200], [128, 0]]], dtype=torch.uint8)

try:
    nn.Conv2d(3, 8, 1)(x.unsqueeze(0))
except RuntimeError as e:
    print("uint8 into the model:", e)

pipelines = {
    "correct":            normalize(x / 255),
    "forgot / 255":       normalize(x.float()),
    "divided by 255 twice": normalize(x / 255 / 255),
    "normalized twice":   normalize(normalize(x / 255)),
}
for name, out in pipelines.items():
    print(f"{name:21} min {out.min():8.2f}  max {out.max():8.2f}")
# uint8 into the model: Input type (unsigned char) and bias type (float) should be the same
# correct               min    -2.04  max     2.25
# forgot / 255          min    -2.04  max  1111.42
# divided by 255 twice  min    -2.12  max    -1.79
# normalized twice      min   -11.12  max     7.70

Feeding uint8 straight to the model raises an error, so that one gets fixed fast. The other three run. Forgetting to divide by 255 sends values up to 1111, far outside the range a pretrained model was trained on. Dividing twice squeezes every pixel into the narrow band from -2.12 to -1.79, so a bright pixel and a dark one look almost the same to the model. Normalizing twice stretches the range to about -11 to 8. In each case the image still displays fine if you convert it back for viewing, which is why these bugs survive a quick visual look.

Integer overflow comes from doing arithmetic on uint8 before converting. A uint8 value wraps around past 255, so 200 + 100 gives 44 instead of 300. Converting to float first avoids it. Image normalization for deep learning works through the 0 to 255 range, standardization and the wraparound in detail.

Color bugs

Color bugs change which colors the model sees:

  • RGB and BGR swapped. Many tools return red, green and blue in that order. OpenCV returns blue first and red last. Read one as the other and skies turn orange while grays stay the same.
  • A grayscale image treated as color. A grayscale photo has one value per pixel. Converting it to RGB repeats that value into three equal channels, so the shape is right. A model trained on color photos then gets inputs where red, green and blue are always equal.
  • A white-balance change between training and deployment. Each camera adjusts colors so white objects look white, and each one does it differently. A model trained on one camera's photos sees shifted colors from a new camera.

Color bugs: RGB and BGR swapped, grayscale treated as color, white balance changed for deployment. Geometry bugs: EXIF rotation not applied, resize stretched the image, x and y swapped between libraries, labels did not move with the image. File bugs: mask saved as JPEG, file only partly decoded, same photo in training and test.

The BGR swap is one line to fix, x[[2, 1, 0]], applied once right after loading. Color spaces explained shows the swap with real pixel values and covers white balance.

Geometry bugs

Geometry bugs put the pixels or the labels in the wrong place:

  • An unapplied EXIF rotation. Phones often save the pixels sideways plus a tag that says how to rotate them for display. Code that ignores the tag trains on sideways photos. PIL.ImageOps.exif_transpose(img) applies it, and the post on file formats and EXIF shows how.
  • A resize that stretched the image. Resizing a 640 by 480 photo to 224 by 224 shrinks the width by about 2.86 times and the height by about 2.14 times, so circles become ovals. Cropping or padding to the right shape first keeps the proportions.
  • x and y swapped between libraries. Box labels are usually written as (x, y), which is column then row. A tensor is indexed as [row, column]. Mixing the two moves every box.
  • Labels that did not move with the image. Flipping, cropping or rotating an image without applying the same change to its boxes, masks or points leaves the labels pointing at the old positions.

The last one is easy to show with a horizontal flip. The object sits in columns 1 and 2 of an 8-pixel-wide image, and its box is (x1, y1, x2, y2) = (1, 1, 3, 3), with x2 and y2 one past the last pixel:

import torch

def hflip(img, box):
    # img: (C, H, W); box: (x1, y1, x2, y2) in pixel edges, x2 and y2 exclusive
    w = img.shape[-1]
    x1, y1, x2, y2 = box
    return torch.flip(img, dims=[-1]), (w - x2, y1, w - x1, y2)

def object_box(img):
    rows, cols = torch.nonzero(img[0], as_tuple=True)
    return (cols.min().item(), rows.min().item(), cols.max().item() + 1, rows.max().item() + 1)

# a 1-channel 4 by 8 image with a small object in columns 1 and 2, rows 1 to 2
img = torch.zeros(1, 4, 8)
img[0, 1:3, 1:3] = 1
box = (1, 1, 3, 3)

flipped_img, flipped_box = hflip(img, box)
print("object after flip:  ", object_box(flipped_img))
print("box left unchanged: ", box)
print("box flipped with it:", flipped_box)
# object after flip:   (5, 1, 7, 3)
# box left unchanged:  (1, 1, 3, 3)
# box flipped with it: (5, 1, 7, 3)

After the flip the object sits in columns 5 and 6. A pipeline that flips only the image keeps the box at columns 1 and 2, around empty pixels, and the model learns that objects look like background. hflip applies the same change to both: the new left edge is w - x2 and the new right edge is w - x1.

File bugs

File bugs come from how the images were saved or collected:

  • A mask saved as JPEG. JPEG blends neighboring values, so a mask with classes 1 and 3 comes back with stray 2s and 4s along every boundary. Save masks as PNG.
  • A file that only partly decodes. A download or a copy that stopped early leaves the file cut short.
  • The same photo in both the training and the test images. The model has already seen those test photos, so the test score is higher than it will be on new photos.

The partly decoded file is a quiet one when a pipeline turns on Pillow's LOAD_TRUNCATED_IMAGES setting to stop crashes:

import io
from PIL import Image, ImageFile

# a dark, grainy 256 by 256 photo whose download stopped at 60 percent of its bytes
buf = io.BytesIO()
Image.effect_noise((256, 256), 40).point(lambda v: v // 4).save(buf, format="JPEG")
data = buf.getvalue()
cut = data[: int(len(data) * 0.6)]

try:
    Image.open(io.BytesIO(cut)).load()
except OSError as e:
    print("default:", e)

ImageFile.LOAD_TRUNCATED_IMAGES = True   # a setting some pipelines turn on
img = Image.open(io.BytesIO(cut))
rows = [[img.getpixel((x, y)) for x in range(256)] for y in range(256)]
flat = sum(all(v == 128 for v in row) for row in rows)
print("loaded size:", img.size)
print("top row mean:", sum(rows[0]) / 256)
print("rows that are flat gray 128:", flat, "of 256")
# default: image file is truncated (9 bytes not processed)
# loaded size: (256, 256)
# top row mean: 31.58203125
# rows that are flat gray 128: 104 of 256

By default Pillow raises an error on the cut file. With the setting on, it loads a full 256 by 256 image whose top rows are the dark photo and whose bottom 104 rows are flat gray. The shape is right and the values are in range, so only looking at the image shows the problem. Leaving the setting off and logging the files that fail is usually the safer choice.

Check the pipeline before the model

When results look wrong, it is tempting to change the model first. Check that the image pipeline gives the model what you think it does:

  1. Look at several real examples straight from the pipeline, after every transform.
  2. Print their shape and dtype.
  3. Print their minimum, maximum and mean.
  4. Check the labels again after every transform: draw the boxes, masks or points on the transformed image.

Check the pipeline before the model: look at several real examples, print shape and dtype, print minimum, maximum and mean, check the labels after every transform, then change the model.

Steps 2 and 3 fit in a few lines. The code below runs them on a batch from a pipeline where someone added a second division by 255 after a step that already divides:

import torch

def check_batch(x):
    # x: a batch straight from the data loader, before it reaches the model
    print(f"shape {tuple(x.shape)}  dtype {x.dtype}  "
          f"min {x.min():.4f}  max {x.max():.4f}  mean {x.mean():.4f}")

torch.manual_seed(0)
decoded = torch.randint(0, 256, (8, 3, 64, 64), dtype=torch.uint8)  # 8 decoded images

loaded = decoded / 255    # what a to-tensor step already does
buggy = loaded / 255      # a second division someone added "to be safe"

check_batch(loaded)
check_batch(buggy)
# shape (8, 3, 64, 64)  dtype torch.float32  min 0.0000  max 1.0000  mean 0.5007
# shape (8, 3, 64, 64)  dtype torch.float32  min 0.0000  max 0.0039  mean 0.0020

The shapes and dtypes match. The maximum of 0.0039 instead of 1 gives the second division away in one line of output. Time spent tuning a model on a broken pipeline is mostly wasted, and the fix is often one line of preprocessing.

Which bugs raise an error

Bug Raises an error? How to catch it
channels-last into a conv yes read the error
alpha channel yes .convert("RGB")
uint8 into the model yes convert to float
reshape instead of permute no look at the image
range or normalization wrong no print min and max
RGB and BGR swapped no look at the image
EXIF rotation not applied no look at the image
labels not moved no draw the labels
truncated file loaded only by default look at the image

Common mistakes

  • Changing the model before checking the data. Print the shape and dtype of a real batch, then its min, max and mean.
  • Using reshape or view to move the channel axis. Use permute.
  • Dividing by 255 in two places. Many to-tensor helpers already divide. Check the max of a batch.
  • Looking at a cleaned-up version of the image. Display the tensor that goes into the model, after every transform, not the file on disk.
  • Applying an augmentation to the image only. Flips, crops and rotations need the same change on boxes, masks and points.
  • Turning on LOAD_TRUNCATED_IMAGES to stop crashes. It hides broken files. Log and remove them instead.

How images are stored as tensors covers (C, H, W) vs (H, W, C), permute and the batch dimension. Image normalization for deep learning covers the 0 to 1 range, the ImageNet mean and std and uint8 overflow. Color spaces explained covers RGB vs BGR and white balance. Image file formats, EXIF orientation, and decoding covers JPEG masks and EXIF rotation.

QuiddityML teaches these bugs as their own concept at the end of the images-as-data unit in its Computer Vision track, and the exercises on it include picking the bug that leaves images looking normal while predictions go wrong, and spotting the extra line in a five-line loading pipeline (QuiddityML).