Sub topic 18
File formats and lossless versus lossy compression
This chapter assumes you know how to compute raw image size from width, height, channels, and bit depth. It also assumes you know what YCbCr and chroma subsampling are. Here you will see how files shrink that raw array, what each family of formats gives up to do it, and which mistakes this causes in computer vision pipelines.
Container, codec, and pixels
A file such as photo.png bundles three things:
- A container: a header and metadata, such as dimensions, bit depth, colour type, and an optional ICC profile.
- A codec: the algorithm that turns the pixel array into fewer bytes.
- The compressed payload the codec produced.
Loading a file means running the codec in reverse and filling an array. After that, the array has the raw size you calculated earlier, whatever the file size was. A 200 KB JPEG of a 1920×1080 photo still occupies 6,220,800 bytes as an 8-bit RGB array. Memory use and GPU transfer costs depend on the array, not the file.
Lossless versus lossy
- Lossless compression lets the decoder recover exactly the array that was encoded. Every sample matches bit for bit.
- Lossy compression discards information the codec judges unimportant. The decoded array is close to the original but not identical.
Lossless codecs exploit redundancy: neighbouring pixels are similar, and repeated patterns can be described briefly. They cannot beat the information content of the data. Noisy photographs compress poorly, while flat graphics compress extremely well.
Lossy codecs also exploit human vision. The eye is less sensitive to fine colour detail than to brightness, and less sensitive to high-frequency texture than to smooth gradients. That is why the lossy pipeline separates luma from chroma.
How a JPEG-style codec works
Baseline JPEG is the standard example of a lossy codec. The steps run in this order.
- Convert to YCbCr. Brightness (Y) is separated from colour (Cb and Cr).
- Subsample chroma. With 4:2:0, Cb and Cr keep one sample per 2×2 block of pixels. This is lossy.
- Block DCT. Each 8×8 block is rewritten as frequency coefficients. This step is mathematically reversible, apart from rounding.
- Quantise. Each coefficient is divided by a table value and rounded. High-frequency coefficients get large divisors and often become zero. This is where most information is lost, and the quality setting controls the table.
- Entropy coding. Huffman coding packs the quantised numbers losslessly.
Because the DCT works on 8×8 blocks, heavy compression produces visible square blocking artefacts. Sharp edges, such as text, show ringing, which looks like faint halos.
Common formats compared
| Format | Compression | Bit depth and channels | Typical use |
|---|---|---|---|
| BMP | None (usually) | 1 to 32 bits per pixel | Simple interchange, legacy tools |
| PNG | Lossless | Grayscale, RGB, palette, optional alpha, 8 or 16 bits per sample | Screenshots, diagrams, masks, labels |
| JPEG | Lossy | 8-bit grayscale or YCbCr, no alpha | Photographs |
| GIF | Lossless, but palette limited to 256 colours | Palette, 1-bit transparency | Simple animation |
| WebP | Lossless or lossy | 8-bit RGB with alpha | Web delivery |
| TIFF | None, lossless, or lossy | Many, including 16-bit and float | Scientific and print work |
| Camera RAW | Usually lossless or light lossy | 12 to 14 bits, sensor mosaic | Photo editing before processing |
GIF is a lossless format, but converting a photo to a 256-colour palette discards colours before the codec runs. The result is lossy overall. Always ask whether a quantisation step happens before the lossless codec.
Measuring the effect
The code below encodes the same synthetic image as PNG and as JPEG, then compares the decoded results with the original. It needs numpy and Pillow.
import io
import numpy as np
from PIL import Image
x = np.linspace(0, 255, 256).astype(np.uint8)
gradient = np.tile(x, (256, 1))
arr = np.stack([gradient, gradient.T, np.full((256, 256), 128, np.uint8)], axis=-1)
def encode(a, fmt, **kwargs):
buf = io.BytesIO()
Image.fromarray(a).save(buf, format=fmt, **kwargs)
return buf.getvalue()
def decode(data):
return np.array(Image.open(io.BytesIO(data)).convert("RGB"))
png = encode(arr, "PNG")
jpg = encode(arr, "JPEG", quality=90)
print("raw bytes:", arr.nbytes) # 196608
print("png bytes:", len(png), "jpeg bytes:", len(jpg)) # exact sizes vary by library version
print("png identical:", np.array_equal(arr, decode(png))) # True
print("jpeg identical:", np.array_equal(arr, decode(jpg))) # False
diff = np.abs(arr.astype(int) - decode(jpg).astype(int))
print("jpeg max error:", diff.max())The PNG round trip is always exact. The JPEG round trip never is, even at high quality. The maximum error is usually small on a smooth gradient and larger near sharp edges.
Cast to int before subtracting. Subtracting uint8 arrays wraps around: 3 - 5 becomes 254, which gives a misleading error.
Choosing a format for vision work
- Training labels and masks: use PNG. A segmentation mask stores class IDs. JPEG blurs the boundary between class 3 and class 7 and can create IDs that do not exist, such as 5. Never store labels as JPEG.
- Photographs for training or inference: JPEG is usually acceptable. Be consistent, though. A model trained on pristine images can degrade on heavily compressed ones, and the reverse also holds. Match the compression of your deployment data.
- Measurements and medical or scientific images: use lossless, high bit depth. 16-bit PNG or TIFF keeps the dynamic range that 8 bits cannot.
- Intermediate results: stay lossless. Saving debug frames as JPEG changes the data you are inspecting.
Metadata also affects results. A JPEG may carry an EXIF orientation tag, and some loaders rotate the pixels while others ignore the tag. The same file can then yield different arrays, with different shape if the tag implies a 90° turn. An embedded ICC profile can likewise change what the values mean if you convert colours.
Common errors
- Generation loss. Each decode, edit, and re-encode as JPEG adds new quantisation error. Edit from a lossless master and export once.
- Judging by file size. Size depends on image content. A noisy image of a given resolution makes a larger PNG than a flat one.
- Assuming file extension equals format. A file named
.jpgmay contain PNG data. Loaders usually check the header, but custom code may not. - Forgetting alpha and palette modes. PNGs may load as 1 channel (palette or gray), 2, 3, or 4. Convert explicitly, as with
.convert("RGB")above, so downstream code sees the shape it expects. - Treating "quality 95" as a percentage. It is an encoder-specific scale for the quantisation tables. Quality 90 in one library need not match quality 90 in another.
- Lossy compression of already lossy data. Re-saving a JPEG at a higher quality does not restore detail. It only makes the file larger.
Exercise
A segmentation dataset stores each mask as a JPEG at quality 95. The masks use class IDs 0 to 10 in a single 8-bit channel. Why is this a problem, and which format should replace it?
Show answer
JPEG is lossy. Quantisation and ringing near class boundaries change pixel values, so a boundary between classes 3 and 7 can decode with intermediate IDs such as 5 that belong to no real region. In a single-channel mask the values are labels, not brightness, so small errors are real mistakes. Use PNG, which is lossless and round-trips the exact IDs.
Exercise
You decode a 4000×3000 JPEG that is 2.4 MB on disk into an 8-bit RGB array. How many bytes does the array occupy, and why is that different from the file size?
Show answer
4000 × 3000 × 3 × 1 = 36,000,000 bytes, about 34.3 MiB. The file stores the compressed payload. Decoding reverses the compression, so the array always has the raw size for its dimensions, channels, and bit depth.