Digital Image Fundamentals: Sampling, Quantisation and Arrays
A lens projects a continuous pattern of light onto a sensor. What reaches your code is a finite grid of integers. Two decisions turn one into the other: sampling decides where the light is measured (how many pixels, how far apart) and quantisation decides how precisely each measurement is stored (how many grey levels). Both throw information away, and both leave traces that models learn from or trip over: jagged edges, false stripes, banding, compression blocks.
This lesson goes one level deeper than Images, audio and video as arrays, which introduced the (H, W, C) array and its dtype. Here you measure what sampling and quantisation cost, see aliasing appear, meet the indexing and dtype bugs that every vision codebase has had at least once, and measure what PNG and JPEG do to the pixels.
Sampling and quantisation
Write the continuous brightness falling on the sensor as . A digital image with pixel pitch and bits per value is
for values on the usual 0–255 scale. Real sensors average the light over each pixel's area rather than reading one point, but the grid is the same. Resolution is the number of samples (); bit depth is the number of levels (). They are independent: a 64 x 64 image can have 16 bits per pixel and a 4000 x 3000 image can have 1. If the rounding error is spread evenly over a bin of width , the mean absolute error of quantisation is .
The first example applies both to the camera test image (a 512 x 512 greyscale photo that ships with scikit-image):
import numpy as np
from skimage import data
img = data.camera()
print("original:", img.shape, img.dtype, "| grey levels used:", len(np.unique(img)))
for k in [2, 4, 8, 16]:
small = img[::k, ::k] # sampling: keep every k-th pixel
print(f"keep every {k:2d}th pixel -> {small.shape[1]:3d} x {small.shape[0]:3d} = {small.size:6d} values")
def quantise(x, bits):
step = 256 // 2 ** bits # bin width Delta
return (x // step) * step + step // 2 # the middle of each bin
for bits in [8, 6, 4, 2, 1]:
q = quantise(img.astype(np.int32), bits)
err = np.abs(q - img).mean()
print(f"{bits} bits: {2 ** bits:3d} levels, mean abs error {err:5.2f}, packed size {img.size * bits // 8:6d} bytes")original: (512, 512) uint8 | grey levels used: 256
keep every 2th pixel -> 256 x 256 = 65536 values
keep every 4th pixel -> 128 x 128 = 16384 values
keep every 8th pixel -> 64 x 64 = 4096 values
keep every 16th pixel -> 32 x 32 = 1024 values
8 bits: 256 levels, mean abs error 0.00, packed size 262144 bytes
6 bits: 64 levels, mean abs error 1.01, packed size 196608 bytes
4 bits: 16 levels, mean abs error 3.92, packed size 131072 bytes
2 bits: 4 levels, mean abs error 14.07, packed size 65536 bytes
1 bits: 2 levels, mean abs error 30.80, packed size 32768 bytes
The errors follow closely: 1.01 for (6 bits), 3.92 for , 14.07 and 30.80 for and , where the photo's uneven histogram makes the rule only approximate. Halving the pixel count in each direction divides the data by 4; removing two bits divides it by only . That is why camera makers spend bits on resolution, and why 8 bits per channel is the default: below about 6 bits, smooth gradients (sky, skin) show visible banding. Medical, astronomy and raw camera images use 10–16 bits because their analysis needs those small differences.
Aliasing: when the grid is too coarse
Sampling is only harmless if the pattern changes slowly compared with the grid. The Nyquist limit says a sampled signal can represent frequencies up to 0.5 cycles per sample (a pattern with a period of at least 2 pixels). Anything finer does not disappear: it aliases, showing up as a false, coarser pattern. A frequency (cycles per sample) appears as
import numpy as np
def dominant_period(sig):
spec = np.abs(np.fft.rfft(sig - sig.mean()))
return 1 / np.fft.rfftfreq(len(sig))[spec.argmax()]
x = np.arange(400)
stripes = np.cos(2 * np.pi * x / 2.5) # 0.4 cycles per pixel: fine stripes
print("true period:", round(float(dominant_period(stripes)), 2), "pixels")
for k in [2, 3]:
s = stripes[::k]
p = float(dominant_period(s))
print(f"every {k}th sample: period {p:.2f} samples = {p * k:.2f} original pixels")
s = stripes[::2]
print(s[:8].round(2).tolist())true period: 2.5 pixels
every 2th sample: period 5.00 samples = 10.00 original pixels
every 3th sample: period 4.96 samples = 14.89 original pixels
[1.0, 0.31, -0.81, -0.81, 0.31, 1.0, 0.31, -0.81]
Stripes with a 2.5-pixel period are 0.4 cycles per pixel. Keeping every second sample makes that 0.8 cycles per sample, above the limit, and the formula predicts : a period of 5 samples, which is 10 original pixels. The printed samples repeat every 5 values. Every third sample gives again, a 15-pixel pattern (14.89 because the FFT has only 134 samples to resolve it). Nothing in the sampled data says these stripes are fake. In photos, aliasing shows up as moiré on fabrics, brick walls and screens, and it is the reason a good downsampler blurs before it drops pixels: resizing measures that.
The array: rows first, pixel centres at half-integers
An image in NumPy is indexed img[row, col] (and img[row, col, channel] for colour). Rows go down, so row is the coordinate and column the coordinate, and img[y, x] is the right way round. Almost every other API is first: OpenCV points (x, y), sizes (width, height), boxes [x1, y1, x2, y2].
Think of pixel (r, c) as the unit square from to and to , with its centre at . Then a box [x1, y1, x2, y2] with exclusive x2, y2 is exactly the set of pixels img[y1:y2, x1:x2], its width is x2 - x1 with no "+1", and its area equals its pixel count. This course uses that convention everywhere; box formats covers the formats that differ. The same half-pixel centres are what resizing gets right or wrong.
import numpy as np
import cv2
cv2.setLogLevel(0)
canvas = np.zeros((6, 12), np.uint8) # H = 6 rows, W = 12 columns
cv2.rectangle(canvas, (8, 1), (10, 3), 255, -1) # OpenCV points are (x, y), corners inclusive
for row in canvas:
print("".join("#" if v else "." for v in row))
rows, cols = np.nonzero(canvas) # NumPy answers in (row, col) order
print("rows", rows.min(), "to", rows.max(), "| cols", cols.min(), "to", cols.max())
print("box [x1, y1, x2, y2] =", [int(cols.min()), int(rows.min()), int(cols.max()) + 1, int(rows.max()) + 1])
try:
canvas[10, 3] # meant x=10, y=3: wrong order
except IndexError as e:
print("IndexError:", e)
img = np.arange(48, dtype=np.uint8).reshape(6, 8)
crop = img[1:3, 2:5] # a crop is a view, not a copy
crop[:] = 0
print("crop shares memory with img:", np.shares_memory(crop, img), "| img[1, 2] is now", int(img[1, 2]))
rgb = np.zeros((4, 4, 3), np.uint8)
bgr = rgb[:, :, ::-1] # reversed channels: a view with a negative stride
print("contiguous:", bgr.flags["C_CONTIGUOUS"], "| strides:", bgr.strides)
try:
cv2.rectangle(bgr, (0, 0), (2, 2), (255, 0, 0), -1)
print("no error")
except cv2.error as e:
print("cv2.error, message mentions the layout:", "Layout" in str(e))
cv2.rectangle(np.ascontiguousarray(bgr), (0, 0), (2, 2), (255, 0, 0), -1)
print("after np.ascontiguousarray: drawing works")............
........###.
........###.
........###.
............
............
rows 1 to 3 | cols 8 to 10
box [x1, y1, x2, y2] = [8, 1, 11, 4]
IndexError: index 10 is out of bounds for axis 0 with size 6
crop shares memory with img: True | img[1, 2] is now 0
contiguous: False | strides: (12, 3, -1)
cv2.error, message mentions the layout: True
after np.ascontiguousarray: drawing works
Three bugs in one example. OpenCV's drawing functions take (x, y) and treat both corners as inclusive, so the rectangle from (8, 1) to (10, 3) is the exclusive box [8, 1, 11, 4]. Indexing with the coordinates swapped either crashes, as here, or, on a square image, silently reads the wrong pixel. A crop is a view into the same memory, so writing into it (drawing a box, normalising in place) changes the original image. And rgb[:, :, ::-1] is also a view, with a negative stride that OpenCV cannot write into; np.ascontiguousarray (or .copy()) makes a normal array.
Data types: uint8, float and the 0–255 versus 0–1 trap
| dtype | range | where you meet it |
|---|---|---|
uint8 |
0–255 integers | decoded PNG/JPEG, OpenCV, most datasets on disk |
uint16 |
0–65535 | 16-bit PNG/TIFF, depth maps, raw sensors (10–14 bits stored in 16) |
float32 / float64 in 0–1 |
scikit-image after img_as_float, PyTorch after ToTensor() |
|
float in 0–255 |
img.astype(np.float32) without dividing: a frequent bug |
Arithmetic on uint8 is arithmetic modulo 256. NumPy keeps the dtype when you add a Python integer, so bright pixels wrap around to dark ones without any warning, and the sum of two images overflows before it is halved:
import numpy as np
import cv2
from skimage import data, img_as_float, img_as_ubyte
cv2.setLogLevel(0)
img = data.camera()
wrapped = img + 60 # uint8 arithmetic wraps around mod 256
saturated = cv2.add(img, 60) # OpenCV saturates at 255
clipped = np.clip(img.astype(np.int16) + 60, 0, 255).astype(np.uint8)
print("dtype of img + 60:", wrapped.dtype, "| bright pixels (> 195) before:", int((img > 195).sum()))
print("img + 60 that wrapped to dark (< 60):", int((wrapped < 60).sum()))
print("cv2.add max", int(saturated.max()), "| same as clip:", np.array_equal(saturated, clipped))
a, b = img, img[:, ::-1]
wrong = (a + b) // 2 # the sum overflows first
right = ((a.astype(np.uint16) + b) // 2).astype(np.uint8)
print("average of two images: wrong mean", round(float(wrong.mean()), 1), "| right mean", round(float(right.mean()), 1))
f1 = img_as_float(img); f2 = img.astype(np.float64)
print("img_as_float range", f1.min(), f1.max(), "| astype(float) range", f2.min(), f2.max())
try:
img_as_ubyte(f2) # floats are expected to be in 0..1
except ValueError as e:
print("ValueError:", str(e)[:60])dtype of img + 60: uint8 | bright pixels (> 195) before: 72087
img + 60 that wrapped to dark (< 60): 72087
cv2.add max 255 | same as clip: True
average of two images: wrong mean 72.4 | right mean 128.8
img_as_float range 0.0 1.0 | astype(float) range 0.0 255.0
ValueError: Images of type float must be between -1 and 1.
Every one of the 72,087 pixels brighter than 195 became darker than 60: the bright sky of the photo turned black. cv2.add saturates instead, and gives exactly what clipping in a wider type gives. The naive average of the image and its mirror has a mean of 72.4 instead of 128.8. The last two lines are the 0–1 versus 0–255 trap: scikit-image's float convention is 0–1, astype(float) keeps 0–255, and a model trained on one and fed the other sees an image 255 times too bright or too dark. Matplotlib's imshow has the same convention for colour images: RGB floats are clipped to 0–1, so a 0–255 float RGB image shows as almost white (single-channel arrays are rescaled to their own min and max instead).
Encoding: PNG, JPEG and bit depth on disk
On disk an image is a compressed byte stream; cv2.imencode and cv2.imdecode do the same as imwrite and imread in memory. To say how much a lossy format changes the pixels, vision uses the peak signal-to-noise ratio
in decibels, infinite for identical images; around 40 dB the difference is hard to see, below about 30 dB it is obvious.
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)
bgr = cv2.cvtColor(data.astronaut(), cv2.COLOR_RGB2BGR) # OpenCV encoders expect BGR
def psnr(a, b):
mse = np.mean((a.astype(np.float64) - b) ** 2)
return float("inf") if mse == 0 else 10 * np.log10(255 ** 2 / mse)
print("raw array:", bgr.nbytes, "bytes")
for label, ext, params in [("PNG", ".png", [cv2.IMWRITE_PNG_COMPRESSION, 3]),
("JPEG q=95", ".jpg", [cv2.IMWRITE_JPEG_QUALITY, 95]),
("JPEG q=75", ".jpg", [cv2.IMWRITE_JPEG_QUALITY, 75]),
("JPEG q=30", ".jpg", [cv2.IMWRITE_JPEG_QUALITY, 30])]:
ok, buf = cv2.imencode(ext, bgr, params)
back = cv2.imdecode(buf, cv2.IMREAD_COLOR)
err = int(np.abs(back.astype(int) - bgr).max())
print(f"{label:9s} {buf.size:7d} bytes ({bgr.nbytes / buf.size:4.1f}x smaller), max error {err:3d}, "
f"PSNR {psnr(back, bgr):5.1f} dB, starts {buf[:3].tobytes().hex()}")
x = bgr
for i in range(10): # save and reload ten times
x = cv2.imdecode(cv2.imencode(".jpg", x, [cv2.IMWRITE_JPEG_QUALITY, 75])[1], cv2.IMREAD_COLOR)
if i in (0, 9):
print(f"after {i + 1:2d} JPEG round trips: PSNR {psnr(x, bgr):.1f} dB")
deep = (np.arange(256 * 256, dtype=np.uint32).reshape(256, 256) % 4096 * 16).astype(np.uint16)
buf = cv2.imencode(".png", deep)[1]
same = cv2.imdecode(buf, cv2.IMREAD_UNCHANGED)
print("16-bit PNG:", same.dtype, "max", int(same.max()), "lossless:", np.array_equal(same, deep))
print("read with IMREAD_COLOR:", cv2.imdecode(buf, cv2.IMREAD_COLOR).dtype, cv2.imdecode(buf, cv2.IMREAD_COLOR).shape)
print("read with IMREAD_GRAYSCALE from the JPEG:", cv2.imdecode(cv2.imencode(".jpg", bgr)[1], cv2.IMREAD_GRAYSCALE).shape)raw array: 786432 bytes
PNG 456059 bytes ( 1.7x smaller), max error 0, PSNR inf dB, starts 89504e
JPEG q=95 99879 bytes ( 7.9x smaller), max error 50, PSNR 38.5 dB, starts ffd8ff
JPEG q=75 40386 bytes (19.5x smaller), max error 76, PSNR 33.8 dB, starts ffd8ff
JPEG q=30 20923 bytes (37.6x smaller), max error 108, PSNR 30.4 dB, starts ffd8ff
after 1 JPEG round trips: PSNR 33.8 dB
after 10 JPEG round trips: PSNR 33.6 dB
16-bit PNG: uint16 max 65520 lossless: True
read with IMREAD_COLOR: uint8 (256, 256, 3)
read with IMREAD_GRAYSCALE from the JPEG: (512, 512)
PNG is lossless and only 1.7 times smaller for this photo. JPEG at quality 95 is 7.9 times smaller at 38.5 dB, yet single pixels are off by up to 50 levels, mostly at sharp edges; at quality 30 it is 37.6 times smaller and 30.4 dB. Re-saving at the same quality costs little more (33.8 to 33.6 dB after ten round trips), but changing quality or cropping between saves adds new loss each time. The first bytes are the file signature (89 50 4e is "\x89PN" for PNG, ff d8 ff starts every JPEG), which is how decoders recognise a file whatever its extension says. The last lines are a quiet trap: a 16-bit PNG is only read as 16 bits with IMREAD_UNCHANGED; the default IMREAD_COLOR converts it to 8-bit, three-channel BGR.
For a training set, the rule of thumb is: masks and labels as PNG (JPEG would blur the class ids), photos as whatever format they were captured in, and the same decoder in training and in production, because different JPEG decoders can differ by a level or two.
Channels-first for PyTorch
NumPy, OpenCV and scikit-image keep channels last, (H, W, C). PyTorch convolutions expect (N, C, H, W), float32, usually normalised with per-channel statistics (ImageNet's mean and standard deviation for pretrained models). The order of operations matters:
import numpy as np
from skimage import data
rgb = data.astronaut()
x = rgb.astype(np.float32) / 255.0 # 0..1 first
mean = np.array([0.485, 0.456, 0.406], np.float32) # ImageNet statistics, RGB order
std = np.array([0.229, 0.224, 0.225], np.float32)
x = (x - mean) / std # broadcasts over the last axis (C)
chw = x.transpose(2, 0, 1) # (C, H, W): a view, no copy
print("transposed:", chw.shape, "contiguous:", chw.flags["C_CONTIGUOUS"], "strides:", chw.strides)
chw = np.ascontiguousarray(chw)
print("copied: ", chw.shape, "contiguous:", chw.flags["C_CONTIGUOUS"], "strides:", chw.strides)
batch = chw[None] # add the batch axis N
print("batch:", batch.shape, batch.dtype, f"{batch.nbytes / 2 ** 20:.1f} MiB")
print("channel means:", [round(float(v), 3) for v in batch.mean(axis=(0, 2, 3))],
"stds:", [round(float(v), 3) for v in batch.std(axis=(0, 2, 3))])
try:
chw - mean # channels are no longer the last axis
except ValueError as e:
print("ValueError:", e)
print("right way after transposing:", (chw - mean[:, None, None]).shape)transposed: (3, 512, 512) contiguous: False strides: (4, 6144, 12)
copied: (3, 512, 512) contiguous: True strides: (1048576, 2048, 4)
batch: (1, 3, 512, 512) float32 3.0 MiB
channel means: [0.306, -0.184, -0.123] stds: [1.405, 1.341, 1.357]
ValueError: operands could not be broadcast together with shapes (3,512,512) (3,)
right way after transposing: (3, 512, 512)
The transpose only changes the strides (4 bytes to the next channel, 12 to the next pixel); np.ascontiguousarray lays the data out channel by channel, which is what torch.from_numpy followed by a convolution wants. After normalisation the channel means are not 0 and the standard deviations not 1, because ImageNet's statistics are not this image's: that is expected, the point is to match what the pretrained network saw during training. Normalising after the transpose with the same mean fails loudly here, but on a 3 x 3 image it would broadcast along the wrong axis and fail silently. Dataset and DataLoader puts this into a pipeline.
Pitfalls
- Swapped coordinates.
img[x, y]instead ofimg[y, x], or(h, w)passed tocv2.resize, which takes(width, height). On square test images the bug is invisible. uint8overflow. Adding, subtracting or averaginguint8arrays wraps around. Convert to a wider type (or float) before arithmetic, clip, convert back.- 0–1 versus 0–255. Check
img.dtypeandimg.max()at every boundary between libraries. A model fed the wrong range still runs and quietly produces nonsense. - Views. Crops, flips and channel reversals are views; writing into them changes the original, and OpenCV cannot write into negative-stride arrays.
- Lossy formats for labels. Never store masks or label maps as JPEG.
- Silent 16-to-8-bit conversion. Read 16-bit data with
IMREAD_UNCHANGED, and check the dtype after loading. - Aliasing at capture or resize. Fine textures sampled too coarsely become false patterns; no later processing can remove them.
Practice
- A 4000 x 3000 photo is stored as 8-bit RGB. How many bytes does the decoded array take, and how many as float32?
Answer
bytes (about 34 MiB) as uint8, four times that (144,000,000 bytes, about 137 MiB) as float32. This is why datasets keep uint8 on disk and in memory and convert each batch to float only when it goes to the model.
- You quantise an image to 3 bits with the mid-bin rule. What is the bin width, and roughly what mean absolute error do you expect?
Answer
levels, so and the expected mean absolute error is about grey levels (exact for an evenly spread histogram, approximate for a photo).
- Stripes have a period of 3 pixels. You keep every second pixel. What period do you see?
Answer
cycle per pixel, so cycle per kept sample, above the limit of 0.5. The alias is cycle per sample: a period of 3 samples, which is 6 original pixels. The stripes look twice as wide as they are.
- OpenCV draws
cv2.rectangle(img, (5, 10), (24, 39), 255, -1). Write the box[x1, y1, x2, y2]in this course's convention, and its width and height.
Answer
OpenCV's corners are inclusive, so the box is [5, 10, 25, 40], width , height , and it covers img[10:40, 5:25].
Test yourself
img is a uint8 array and a pixel has value 230. What does img + 40 give for that pixel?
- 255
- 270
- 14
- an OverflowError
Which statement about resolution and bit depth is correct?
- They are the same thing measured in different units
- Resolution is the number of samples, bit depth the number of levels per sample; they are independent
- Higher resolution always needs more bits per pixel
- Bit depth decides how many pixels the image has
In this course a box is [x1, y1, x2, y2] with exclusive x2, y2. Which NumPy slice selects its pixels?
img[x1:x2, y1:y2]img[y1:y2, x1:x2]img[y1:y2 + 1, x1:x2 + 1]img[x1:y1, x2:y2]
The lesson's astronaut photo saved as JPEG at quality 95 had a PSNR of 38.5 dB. What does that mean?
- The file is lossless
- The mean squared error is small but not zero; single pixels can still be far off
- 38.5 % of the pixels changed
- The file is 38.5 times smaller
Why does cv2.rectangle(rgb[:, :, ::-1], ...) raise an error?
- OpenCV cannot draw on colour images
- The reversed-channel array is a view with a negative stride, which OpenCV cannot write into
- The colour must be given in RGB
- Rectangles need float images