Sub topic 2
Width, height, and resolution
This chapter assumes you can read NumPy array shapes and know that an image is a grid of numbers. Basic Python is enough. By the end you should be able to read an image's dimensions without mixing up the axes, say precisely what "resolution" refers to, and predict what happens when you shrink an image.
Width and height are counts of samples
An image's width is the number of pixel columns. Its height is the number of pixel rows. Both are plain integers with no unit. A 640×480 image has 640 columns and 480 rows, so it holds 307,200 pixels.
Photo specifications often quote megapixels, which is pixel count divided by one million. A 6000×4000 image has 24,000,000 pixels, or 24 megapixels. Megapixels count samples. They say nothing about sharpness, because a blurry image can have a high pixel count.
The aspect ratio is width divided by height. 1920×1080 gives 16:9, and 640×480 gives 4:3. Resizing to a different aspect ratio stretches the content unless you crop or pad it.
Axis order is the most common source of bugs
Libraries disagree about whether width or height comes first.
| Library or call | Order | Example for a 640-wide, 480-high image |
|---|---|---|
| NumPy `array.shape` | (height, width, channels) | `(480, 640, 3)` |
| Pillow `Image.size` | (width, height) | `(640, 480)` |
| OpenCV `cv2.resize(img, dsize)` | `dsize` is (width, height) | `(640, 480)` |
| OpenCV `img.shape` | (height, width, channels) | `(480, 640, 3)` |
The array order follows the row-major reading of a matrix: the first index picks the row, which is the vertical position. The Pillow and OpenCV size arguments follow the Cartesian convention of x first, then y.
import numpy as np
from PIL import Image
arr = np.zeros((480, 640, 3), dtype=np.uint8)
height, width = arr.shape[:2]
print(height, width) # 480 640
img = Image.fromarray(arr)
print(img.size) # (640, 480)
# Indexing is [row, column], that is [y, x]
arr[10, 200] = (255, 0, 0) # row 10 (near the top), column 200A swapped pair raises no error when you pass a square size, and it only fails on the first non-square image. Write height, width = arr.shape[:2] explicitly and keep those names throughout your code.
What "resolution" means
The word is used in at least three ways, and mixing them up causes confusion.
- Pixel dimensions. "A 1920×1080 image" describes how many samples exist. This is the meaning that matters for storage and for neural-network input sizes.
- Pixel density. PPI (pixels per inch) or DPI (dots per inch) says how many pixels are laid out per unit of physical length, on a screen or a printed page.
- Spatial detail. This is how much real-world detail the image actually captures. It depends on the lens, the sensor, focus, and motion blur, as well as on pixel count.
Pixel density is stored in a file as metadata. It does not change the pixels. Setting a photo to 300 DPI instead of 72 DPI leaves every pixel value and the file's dimensions unchanged. It only changes the physical size a printer or layout program will choose.
def print_size_inches(width_px, height_px, ppi):
"""Physical size a printer would use at the given pixel density."""
return width_px / ppi, height_px / ppi
w, h = 6000, 4000
print(w * h / 1e6) # 24.0 megapixels
print(print_size_inches(w, h, 300)) # (20.0, 13.333333333333334)
print(print_size_inches(w, h, 72)) # (83.33333333333333, 55.55555555555556)The same 24-megapixel image prints at about 20×13 inches at 300 PPI, or about 83×56 inches at 72 PPI. Only the assumed density changed.
Changing the resolution means resampling
To change width and height you must create a new grid and decide what value each new pixel gets. This is resampling. Making the grid smaller is downsampling. Making it larger is upsampling. Upsampling cannot add detail that was never captured. It only interpolates between existing samples, so the result is bigger but not sharper.
The simplest downsample takes every second pixel. That is fast but dangerous. Fine patterns that repeat faster than the new grid can represent get misread as something else. This is aliasing. A safer approach averages each block of source pixels.
import numpy as np
def downsample_2x(img):
"""Halve width and height by averaging each 2x2 block."""
h, w = img.shape[:2]
h2, w2 = h - h % 2, w - w % 2 # drop an odd last row/column
img = img[:h2, :w2].astype(np.float32)
blocks = img.reshape(h2 // 2, 2, w2 // 2, 2, *img.shape[2:])
return blocks.mean(axis=(1, 3)).round().astype(np.uint8)
small = downsample_2x(np.arange(24, dtype=np.uint8).reshape(4, 6))
print(small.shape) # (2, 3)
print(small) # [[ 4 6 8]
# [16 18 20]]
# Alternating black and white columns
stripes = np.tile(np.array([0, 255], dtype=np.uint8), (4, 4)) # shape (4, 8)
print(stripes[:, ::2]) # naive skipping: every value is 0
print(downsample_2x(stripes)) # averaging: every value is 128Skipping pixels turns a black-and-white stripe pattern into solid black. Averaging turns it into mid grey, which is the honest summary of the area. Production resizers such as Pillow's Image.resize with Image.Resampling.LANCZOS or BOX apply filters like this for you. Common choices are nearest-neighbour, bilinear, bicubic, and Lanczos. Nearest-neighbour is fastest and keeps hard edges, so it suits label maps where values must not be blended. The smoother filters suit photographs.
Edge cases and common errors
- Odd dimensions. A 2× downsample of a 5-pixel-wide image has no clean answer. The function above crops the extra column. Other tools pad or round, so output sizes can differ by one pixel between libraries.
- Non-square inputs to models. Resizing a 4:3 photo to 224×224 distorts it. Many pipelines instead resize the short side and then crop, or pad to a square.
- Metadata orientation. A phone photo may be stored as 4000×3000 with an EXIF tag saying "rotate 90°". The array shape you load may be landscape even though the viewer shows portrait.
- Trusting PPI. Do not use the DPI field to decide whether an image is "high resolution". Check the pixel dimensions.
- Resizing label images. Interpolating class IDs such as 3 and 7 can create an ID of 5 that matches no class. Use nearest-neighbour for those.
Exercise
A scanned page is 2550×3300 pixels and is tagged 300 PPI. (a) What is its physical size in inches? (b) You change the tag to 150 PPI without touching the pixels. What are the new physical size and pixel dimensions? (c) In NumPy, what does shape report for the original?
Show answer
(a) 2550 / 300 = 8.5 inches wide and 3300 / 300 = 11 inches high, which is US Letter. (b) The physical size becomes 17 × 22 inches, and the pixel dimensions stay 2550×3300, because PPI is only metadata. (c) (3300, 2550) for a grayscale array, or (3300, 2550, 3) for RGB, since NumPy lists height first.