Image file formats, EXIF orientation, and decoding: what ML code needs to know
How JPEG and PNG change the pixels your model trains on, why a phone photo can load sideways, what EXIF metadata leaks, and how to check a decoded image in PyTorch before it reaches the model.
An image file format is the set of rules for writing a picture to disk: what gets stored, what gets thrown away and how the rest is packed into fewer bytes. Loading the file runs those rules in reverse and gives back a grid of pixel values. For machine learning this step is easy to overlook, because a format can change the pixels, drop a channel or hide a rotation without raising an error. The model then trains on numbers that differ from the ones you think you saved.
What a file format decides
The same picture saved as .jpg, .png and .tiff gives three different sequences of bytes on disk.

An image file has four separate parts:
- the container is the file wrapper, the structure that says where each piece of the file starts
- the encoding is how the pixel values are compressed into bytes
- the metadata is extra information about the picture, such as when it was taken
- the decoded pixels are the grid of values you get back when you load the file
The file extension only hints at the first two. A file named photo.png that someone renamed from photo.jpg still holds JPEG bytes.
Lossy, lossless and uncompressed
Compression formats fall into three groups:
- Lossy formats like JPEG throw away some information to make the file smaller.
- Lossless formats like PNG compress without throwing anything away, so the decoded pixels are exactly the values that were saved.
- Uncompressed formats store every value directly. The files are the biggest and the pixels come back unchanged.

The code below saves one small photo-like image in memory as PNG and as JPEG, loads each one back and measures how far the decoded pixels are from the originals. The image is a 64 by 64 brightness ramp with a white square in the middle and some random noise, which is closer to a real photo than a flat color.
import io
import torch
from PIL import Image
def to_pil(x):
# x: (H, W, 3) uint8 tensor
h, w, _ = x.shape
return Image.frombytes("RGB", (w, h), bytes(x.flatten().tolist()))
def to_tensor(img):
w, h = img.size
return torch.tensor(list(img.tobytes()), dtype=torch.uint8).view(h, w, -1)
def round_trip(x, fmt, **opts):
buf = io.BytesIO()
to_pil(x).save(buf, format=fmt, **opts) # encode to bytes in memory
size = buf.tell()
buf.seek(0)
return to_tensor(Image.open(buf).convert("RGB")), size # decode
# a 64 by 64 photo-like image: a left-to-right ramp, a white square and sensor-style noise
torch.manual_seed(0)
ramp = torch.linspace(20, 200, 64).view(1, 64, 1).expand(64, 64, 3)
noisy = ramp + torch.randn(64, 64, 3) * 8
noisy[24:40, 24:40] = 250
x = noisy.round().clamp(0, 255).to(torch.uint8)
for fmt, opts in [("PNG", {}), ("JPEG", {"quality": 90}), ("JPEG", {"quality": 30})]:
back, size = round_trip(x, fmt, **opts)
diff = (back.int() - x.int()).abs()
print(f"{fmt} {opts}: {size} bytes, mean error {diff.float().mean():.2f}, max error {diff.max().item()}")
# PNG {}: 8222 bytes, mean error 0.00, max error 0
# JPEG {'quality': 90}: 1738 bytes, mean error 5.59, max error 32
# JPEG {'quality': 30}: 781 bytes, mean error 6.06, max error 31round_trip encodes the tensor into an in-memory file with Pillow and decodes it again, so no file touches the disk. PNG comes back with an error of 0 on every pixel. JPEG at quality 90 makes the file almost five times smaller than PNG, and in exchange the average pixel moves by about 5.6 out of 255 and some pixels move by 32. Lowering the quality to 30 shrinks the file further and moves the pixels a little more.
What JPEG does to an image
JPEG shrinks a file by dropping detail the eye is less likely to miss, and the quality setting controls how much it drops. Re-saving a JPEG can drop more each time, especially when the quality changes or the image is edited between saves.
The lost detail shows up in three ways:
- blocking: false edges along an 8 by 8 grid and flat patches, because JPEG compresses each 8 by 8 block of pixels on its own
- ringing: halos around sharp edges and text
- banding: smooth gradients flattened into steps

These artifacts change what a model sees. Blocking can create false edges for an object detector to respond to, and ringing around letters can break text reading.
When JPEG is safe to use
JPEG is fine for ordinary photos where small pixel changes do not change the answer, such as the inputs to many image classifiers. A photo of a dog is still a photo of a dog after its pixels move by a few values.
It is risky for images where exact values carry the answer:
- segmentation masks, where each pixel stores a class number
- diagrams and crops of text, which have sharp edges that ringing blurs
- restoration targets, the clean images a denoising or deblurring model learns to produce
- measurement images, where a pixel value is a reading such as a temperature
- test data whose scores depend on exact pixel values

PNG keeps the exact pixels
PNG compresses without loss, so a pixel saved as 200 comes back as 200. It also supports an alpha channel, a fourth number per pixel that stores transparency. For photos, PNG files are larger than JPEG files, as the 8222 bytes against 1738 bytes above show.

Why a mask should not be saved as JPEG
A segmentation mask is a label image the same size as the photo that stores a class number in every pixel, such as 0 for background and 3 for car. JPEG blends neighboring values and adds ringing around edges. So a boundary between class 1 and class 3 comes back with values that were not in the original mask:
import io
import torch
from PIL import Image
# a 16 by 16 segmentation mask: class 1 on the left, class 3 from column 5 on
mask = torch.ones(16, 16, dtype=torch.uint8)
mask[:, 5:] = 3
def save_and_load(mask, fmt):
h, w = mask.shape
buf = io.BytesIO()
Image.frombytes("L", (w, h), bytes(mask.flatten().tolist())).save(buf, format=fmt)
buf.seek(0)
img = Image.open(buf)
return torch.tensor(list(img.tobytes()), dtype=torch.uint8).view(h, w)
for fmt in ["PNG", "JPEG"]:
back = save_and_load(mask, fmt)
wrong = (back != mask).sum().item()
print(f"{fmt}: classes {back.unique().tolist()}, {wrong} of 256 pixels wrong")
print("row 0 after JPEG:", save_and_load(mask, "JPEG")[0].tolist())
# PNG: classes [1, 3], 0 of 256 pixels wrong
# JPEG: classes [1, 2, 3, 4], 48 of 256 pixels wrong
# row 0 after JPEG: [2, 1, 1, 1, 1, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3, 3]The PNG mask comes back with the two classes it had. The JPEG mask now holds classes 2 and 4, which nobody labeled, and 48 of its 256 pixels have the wrong class. Row 0 shows where they sit: a 2 next to the boundary and a 4 right after it.

Classes 2 and 4 are valid class numbers, so no error is raised and a range check does not catch them. The mask now carries a band of wrong classes along every object boundary, which is where segmentation scores are most sensitive. Save masks and other label images in a lossless format such as PNG.
What a format can carry
Formats also differ in what they can hold beyond the pixel colors, and saving in one that cannot hold what you need drops it without a warning:
- Transparency: only some formats keep an alpha channel. The rest flatten the image onto a background color.
- Bit depth: the number of bits used to store each value. Standard JPEG stores 8 bits per channel, which gives values from 0 to 255. Medical and scientific formats can store 16-bit values, from 0 to 65,535.
- Metadata: formats differ in whether they keep the orientation and camera settings, or the location and timestamps.

EXIF: the metadata inside a photo
Metadata records how, when and where a photo was taken, and what happened to it afterward. In photos it is usually stored as EXIF, short for Exchangeable Image File Format.
Common EXIF fields include the timestamp, the orientation and the camera model. Others hold the lens, the focal length and the exposure settings. Some hold GPS coordinates and editing history.

Why a photo can load sideways
A phone camera often saves the pixels in the sensor's own orientation, whichever way the phone was held. It then writes an orientation field into the EXIF that says how to rotate those pixels for display. Photo viewers read the field and show the picture upright. Code that decodes only the pixels skips that step, so the image arrives in the training loop sideways or upside down.
The code below builds such a file: a 400 by 300 stored image with orientation 6, which means "rotate 90 degrees clockwise to display". Pillow's ImageOps.exif_transpose applies the rotation and removes the tag, so it cannot be applied twice.
import io
from PIL import Image, ImageOps
ORIENTATION = 0x0112 # EXIF tag 274: how to rotate the stored pixels for display
# a phone held upright stores a 400 wide by 300 tall sensor image,
# plus orientation 6, which means "rotate 90 degrees clockwise to display"
stored = Image.new("RGB", (400, 300), "gray")
exif = Image.Exif()
exif[ORIENTATION] = 6
buf = io.BytesIO()
stored.save(buf, format="JPEG", exif=exif)
buf.seek(0)
img = Image.open(buf)
print("orientation tag:", img.getexif().get(ORIENTATION))
print("pixels as stored (w, h):", img.size)
upright = ImageOps.exif_transpose(img)
print("after applying the tag (w, h):", upright.size)
print("tag left after transpose:", upright.getexif().get(ORIENTATION))
# orientation tag: 6
# pixels as stored (w, h): (400, 300)
# after applying the tag (w, h): (300, 400)
# tag left after transpose: NoneWithout exif_transpose the model gets a 400 by 300 image of something that was photographed upright. If the dataset has boxes or keypoints drawn on the upright photo, they no longer match the pixels either. Call it right after opening the file, before any resize or crop.
How metadata helps when debugging
The orientation field explains a sideways image. Timestamps and camera models let you group photos by capture session, so near-identical shots from one session do not end up in both the training and the test images. Focal length and exposure settings help explain why a new camera's photos look different from the training photos.

The privacy risk
GPS coordinates in a photo reveal where someone was, and timestamps reveal when. Camera serial numbers can link photos to one person. Sharing a dataset without stripping its metadata can leak this information.

One way to strip it is to copy the pixels into a fresh image, which starts with no EXIF block, and save that:
import io
from PIL import Image
def strip_metadata(img):
# copy only the pixels into a fresh image, so no EXIF block comes along
clean = Image.new(img.mode, img.size)
clean.paste(img)
return clean
# a photo with a camera model and a timestamp in its EXIF
photo = Image.new("RGB", (64, 48), "gray")
exif = Image.Exif()
exif[0x0110] = "PhoneCam X" # tag 272: camera model
exif[0x0132] = "2026:11:29 09:41:00" # tag 306: date and time
buf = io.BytesIO()
photo.save(buf, format="JPEG", exif=exif)
buf.seek(0)
img = Image.open(buf)
print("before:", dict(img.getexif()))
out = io.BytesIO()
strip_metadata(img).save(out, format="JPEG")
out.seek(0)
print("after: ", dict(Image.open(out).getexif()))
# before: {272: 'PhoneCam X', 306: '2026:11:29 09:41:00'}
# after: {}Stripping also removes the orientation field, so apply exif_transpose first and strip second. Re-saving as JPEG compresses the pixels again too, so for a lossless copy save the clean image as PNG.
The modeling risk
If a label happens to match a metadata field, a model given that metadata can predict the label from the camera model instead of the image. For example, if every damaged part in a factory dataset was photographed by the inspection camera and every intact part by a different one, the camera model alone predicts the label. That is a shortcut, and it stops working as soon as the camera no longer matches the label.

Decoding: from bytes to a pixel array
A file on disk is a sequence of bytes, not a pixel array. A PNG file starts with the bytes \x89PNG, and a JPEG file starts with FF D8 FF. Decoding reverses the format's compression and produces a grid of values with a shape and a dtype, the data type of each value, such as uint8 for whole numbers from 0 to 255.

Showing the decoded grid on screen adds more changes, such as rescaling the picture to fit the window and sometimes an orientation fix. What you see in an image viewer is not always exactly what the array holds.
Two channel orders
Many tools return color channels as red, green, blue. Some, such as OpenCV, return blue first and red last. Read BGR as RGB and red and blue swap, so skies turn orange and skin turns bluish, while grays stay the same. Color spaces explained covers the swap and its one-line fix, x[[2, 1, 0]].
Checking a decoded image
After decoding, check six things. The first three are shape, dtype and value range, and they fit in one short function. The code below decodes a PNG logo with a transparent background, the kind of file that is common on the web, and runs the function on it:
import io
import torch
from PIL import Image
def decode(file_bytes):
# bytes on disk -> (C, H, W) tensor, exactly as the file stores it
img = Image.open(io.BytesIO(file_bytes))
w, h = img.size
c = len(img.getbands())
return torch.tensor(list(img.tobytes()), dtype=torch.uint8).view(h, w, c).permute(2, 0, 1)
def inspect_image(x):
info = {}
info['shape'] = tuple(x.shape)
info['dtype'] = x.dtype
info['min'] = x.min().item()
info['max'] = x.max().item()
return info
# a 224 by 224 PNG logo with a transparent background, as many web images are
buf = io.BytesIO()
logo = Image.new("RGBA", (224, 224), (0, 0, 0, 0))
logo.paste((255, 200, 0, 255), (56, 56, 168, 168))
logo.save(buf, format="PNG")
file_bytes = buf.getvalue()
print(file_bytes[:8])
print(inspect_image(decode(file_bytes)))
# b'\x89PNG\r\n\x1a\n'
# {'shape': (4, 224, 224), 'dtype': torch.uint8, 'min': 0, 'max': 255}The first line confirms the bytes are a PNG file. The second line shows two problems at once. The shape starts with 4, so the image has an alpha channel and a model built for 3 channels will fail on it. The values run from 0 to 255 as uint8, so a model that expects decimals from 0 to 1 gets numbers 255 times too large. Converting with .convert("RGB") before decoding drops the alpha channel, and dividing by 255 fixes the range.

The other three checks are channel order, orientation and how the image looks, and they need your eyes. Swapping RGB and BGR leaves the shape and the range untouched. Rotating by 90 degrees leaves the range untouched and only swaps height and width, so the reliable check is to display the array and look at it.

Common mistakes
- Saving masks or label images as JPEG. The decoded mask gains class numbers nobody labeled. Use PNG.
- Re-saving training images as JPEG during preprocessing. Each save can move the pixels further from the original. Keep the original files and save processed copies losslessly.
- Ignoring EXIF orientation. Photos arrive sideways, and boxes drawn on the upright photo stop matching. Call
ImageOps.exif_transposeright after opening the file. - Trusting the file extension. A
.pngname does not guarantee PNG bytes. The first bytes of the file tell you the real format. - Feeding an RGBA image to a 3-channel model. Convert to RGB, or check that the shape starts with 3.
- Sharing a dataset with its metadata. GPS, timestamps and serial numbers go with the files. Strip them before release.
- Letting metadata predict the label. If one camera took all the photos of one class, the model can learn the camera. Mix cameras across classes, or keep the metadata away from the model.
Related concepts
How images are stored as tensors covers the shape a decoded image should have and how to drop an alpha channel. Image normalization for deep learning covers turning 0 to 255 into the range a model expects, and what bit depth changes. How a camera makes an image shows where JPEG compression and the metadata are added inside the camera.
QuiddityML teaches file formats, metadata and decoding in the images-as-data unit of its Computer Vision track. The exercises there include writing inspect_image from scratch, filling in the BGR-to-RGB fix and spotting the bug in a broken version of it (QuiddityML).