Resizing, Cropping and Geometric Transforms
Models take a fixed input size, cameras do not deliver it, and augmentations rotate, flip and warp images on purpose. Every such step moves pixels, and two things can go wrong: the image itself (blurry, aliased, shifted by half a pixel) and its annotations (boxes and points that no longer sit on the objects). Underneath every geometric operation is the same recipe: for each output pixel, compute where it comes from in the input, and interpolate the input there. This lesson writes bilinear interpolation from scratch and matches OpenCV to float precision, measures aliasing when downsampling, extends image preparation's letterbox with the inverse mapping that brings predictions back to the original image, and builds affine and perspective transforms from their matrices (geometric transformations has the linear algebra).
Inverse mapping and pixel centres
To resize an image to , a resampler loops over the output pixels and asks which input position each one corresponds to (inverse mapping, so that every output pixel gets exactly one value). With pixel centres at half-integers (digital images), output pixel has its centre at , which in input units is , so the input index is
This half-pixel convention keeps the image centred: output and input pixel centres line up geometrically. The naive shifts the whole image by up to half a pixel, which is harmless for a photo and very visible for a mask or a small object. Then interpolation decides the value at the non-integer position:
- nearest: the closest input pixel (the only correct choice for label maps and masks);
- bilinear: a weighted mean of the 4 surrounding pixels, with fractional parts ;
- bicubic: a cubic through 4 x 4 pixels; sharper, and it can overshoot the input range;
- area: when shrinking, the average of all input pixels the output pixel covers (a box filter), which avoids aliasing.
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)
def resize_bilinear(img, new_h, new_w):
h, w = img.shape
ys = np.clip((np.arange(new_h) + 0.5) * h / new_h - 0.5, 0, h - 1) # half-pixel mapping
xs = np.clip((np.arange(new_w) + 0.5) * w / new_w - 0.5, 0, w - 1)
y0, x0 = np.floor(ys).astype(int), np.floor(xs).astype(int)
y1, x1 = np.minimum(y0 + 1, h - 1), np.minimum(x0 + 1, w - 1)
wy, wx = (ys - y0)[:, None], (xs - x0)[None, :]
top = img[y0][:, x0] * (1 - wx) + img[y0][:, x1] * wx
bottom = img[y1][:, x0] * (1 - wx) + img[y1][:, x1] * wx
return top * (1 - wy) + bottom * wy
row = np.array([[0, 100, 200, 250]], np.float32)
print("source:", row[0].tolist())
print("from scratch bilinear:", resize_bilinear(row, 1, 8)[0].round(1).tolist())
for name, flag in [("INTER_NEAREST", cv2.INTER_NEAREST), ("INTER_NEAREST_EXACT", cv2.INTER_NEAREST_EXACT),
("INTER_LINEAR", cv2.INTER_LINEAR), ("INTER_CUBIC", cv2.INTER_CUBIC), ("INTER_AREA", cv2.INTER_AREA)]:
print(f"{name:20s}", [round(float(v), 1) for v in cv2.resize(row, (8, 1), interpolation=flag)[0]])
print("down 4 -> 2: NEAREST", cv2.resize(row, (2, 1), interpolation=cv2.INTER_NEAREST)[0].tolist(),
"NEAREST_EXACT", cv2.resize(row, (2, 1), interpolation=cv2.INTER_NEAREST_EXACT)[0].tolist(),
"LINEAR", cv2.resize(row, (2, 1), interpolation=cv2.INTER_LINEAR)[0].tolist(),
"AREA", cv2.resize(row, (2, 1), interpolation=cv2.INTER_AREA)[0].tolist())
img = data.camera().astype(np.float32)
for (h, w) in [(700, 900), (300, 200)]:
d = np.abs(resize_bilinear(img, h, w) - cv2.resize(img, (w, h), interpolation=cv2.INTER_LINEAR)).max()
print(f"camera 512x512 -> {w}x{h}: max |ours - cv2| = {d:.4f}")
u8 = cv2.resize(data.camera(), (900, 700), interpolation=cv2.INTER_LINEAR).astype(np.float32)
print("uint8 input (fixed-point inside OpenCV): max diff", round(float(np.abs(u8 - resize_bilinear(img, 700, 900)).max()), 3))source: [0.0, 100.0, 200.0, 250.0]
from scratch bilinear: [0.0, 25.0, 75.0, 125.0, 175.0, 212.5, 237.5, 250.0]
INTER_NEAREST [0.0, 0.0, 100.0, 100.0, 200.0, 200.0, 250.0, 250.0]
INTER_NEAREST_EXACT [0.0, 0.0, 100.0, 100.0, 200.0, 200.0, 250.0, 250.0]
INTER_LINEAR [0.0, 25.0, 75.0, 125.0, 175.0, 212.5, 237.5, 250.0]
INTER_CUBIC [-10.5, 19.1, 66.8, 131.4, 175.6, 221.9, 242.2, 255.3]
INTER_AREA [0.0, 0.0, 100.0, 100.0, 200.0, 200.0, 250.0, 250.0]
down 4 -> 2: NEAREST [0.0, 200.0] NEAREST_EXACT [100.0, 250.0] LINEAR [50.0, 225.0] AREA [50.0, 225.0]
camera 512x512 -> 900x700: max |ours - cv2| = 0.0028
camera 512x512 -> 200x300: max |ours - cv2| = 0.0025
uint8 input (fixed-point inside OpenCV): max diff 0.763
Upsampling 4 to 8 pixels, output pixel 1 maps to input position , a quarter of the way from 0 to 100: 25.0. The from-scratch function reproduces INTER_LINEAR exactly on the row and to 0.003 on the photo, for enlarging and shrinking; with uint8 input OpenCV uses fixed-point weights and rounds, so results differ by up to 0.76 of a level. Cubic overshoots ( and ): clip before converting back to uint8, and never use it on masks. Two traps hide in the downsampling line. INTER_NEAREST picks input (pixels 0 and 2, so the image shifts left by half a pixel), while INTER_NEAREST_EXACT uses the half-pixel rule (pixels 1 and 3, the true centres); other libraries (PIL, PyTorch's interpolate, TensorFlow) each have their own defaults, a known source of train/serve skew. And for an exact factor of 2, INTER_LINEAR and INTER_AREA agree; they differ when the factor is larger.
Aliasing when shrinking
Downsampling by a factor lowers the Nyquist limit from 0.5 to cycles per original pixel. Detail finer than that does not vanish; it aliases into false coarse patterns (moiré on shirts, bricks and screens). The cure is to low-pass filter first, which is exactly what INTER_AREA (averaging) or an explicit Gaussian blur does. The test: stripes with a period of 4.4 pixels, shrunk 4 times.
import numpy as np
import cv2
cv2.setLogLevel(0)
x = np.arange(512)
stripes = np.tile((128 + 100 * np.sin(2 * np.pi * x / 4.4)).astype(np.float32), (64, 1))
def dominant_period(row):
spec = np.abs(np.fft.rfft(row - row.mean()))
return 1 / np.fft.rfftfreq(len(row))[spec.argmax()]
print(f"input: period {dominant_period(stripes[0]):.2f} px, contrast (std) {stripes.std():.1f}")
small = {"every 4th pixel": stripes[:, ::4],
"INTER_NEAREST": cv2.resize(stripes, (128, 16), interpolation=cv2.INTER_NEAREST),
"INTER_LINEAR": cv2.resize(stripes, (128, 16), interpolation=cv2.INTER_LINEAR),
"INTER_AREA": cv2.resize(stripes, (128, 16), interpolation=cv2.INTER_AREA),
"Gaussian s=2 + every 4th": cv2.GaussianBlur(stripes, (0, 0), 2)[:, ::4]}
for name, s in small.items():
print(f"{name:25s} -> {s.shape[1]} px wide: std {s.std():6.2f}, apparent period {dominant_period(s[0]):6.2f} px = {4 * dominant_period(s[0]):6.1f} original px")input: period 4.41 px, contrast (std) 70.7
every 4th pixel -> 128 px wide: std 70.29, apparent period 10.67 px = 42.7 original px
INTER_NEAREST -> 128 px wide: std 70.29, apparent period 10.67 px = 42.7 original px
INTER_LINEAR -> 128 px wide: std 53.62, apparent period 10.67 px = 42.7 original px
INTER_AREA -> 128 px wide: std 7.63, apparent period 10.67 px = 42.7 original px
Gaussian s=2 + every 4th -> 128 px wide: std 2.80, apparent period 10.67 px = 42.7 original px
The stripes are cycles per pixel; after keeping every 4th pixel that is 0.909 cycles per sample, which aliases to : a period of 11 output pixels (the FFT on 128 samples resolves it as 10.67), or about 44 original pixels. Nearest-neighbour keeps the fake stripes at full contrast (std 70.3, the same as the real stripes), bilinear barely helps (53.6) because it only looks at 2 pixels per output, INTER_AREA averages 4 and cuts the false pattern to 7.6, and a Gaussian with before subsampling to 2.8. The fake period is the same in every row: what differs is how much of the fake pattern survives. Rule: shrink with INTER_AREA (or blur first), enlarge with INTER_LINEAR or INTER_CUBIC, resize masks with INTER_NEAREST. Image augmentation and modern training libraries (antialias=True in torchvision) follow the same rule.
Crop, pad and letterbox, forwards and back
Cropping is slicing, img[y1:y2, x1:x2], and every box inside moves by (and must be clipped to the crop). A letterbox scales the image by to fit an square without distortion and pads the rest with a constant grey (114 in YOLO's convention). A box transforms as for padding on the left and top, and the detector's predictions come back to the original image with the inverse, . YOLO-style "minimal" letterboxing pads only up to the next multiple of the network stride (32) instead of the full square, which saves computation on wide images.
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)
def letterbox(img, new=640, pad_value=114, stride=32, auto=False):
h, w = img.shape[:2]
r = min(new / h, new / w)
nh, nw = round(h * r), round(w * r)
ph, pw = new - nh, new - nw
if auto: # pad only to a multiple of the stride
ph, pw = ph % stride, pw % stride
top, left = ph // 2, pw // 2
out = cv2.resize(img, (nw, nh), interpolation=cv2.INTER_LINEAR)
out = cv2.copyMakeBorder(out, top, ph - top, left, pw - left, cv2.BORDER_CONSTANT, value=(pad_value,) * 3)
return out, r, (left, top)
img = data.coffee() # 600 x 400
box = np.array([168, 17, 423, 326], float) # a box around the cup
for auto in [False, True]:
out, r, (left, top) = letterbox(img, 640, auto=auto)
fwd = box * r + [left, top, left, top] # into the network's input
back = (fwd - [left, top, left, top]) / r # predictions back to the original
print(f"auto={auto!s:5s}: {img.shape[1]}x{img.shape[0]} -> {out.shape[1]}x{out.shape[0]}, scale {r:.4f}, pad left/top {left}/{top}")
print(f" box {box.astype(int).tolist()} -> {fwd.round(1).tolist()} -> back {back.round(2).tolist()}")
print("pad pixel value:", out[0, 0].tolist())
sx, sy = 640 / img.shape[1], 640 / img.shape[0] # stretching instead of letterboxing
sbox = box * [sx, sy, sx, sy]
print(f"stretched instead: box aspect w/h {(box[2] - box[0]) / (box[3] - box[1]):.3f} -> {(sbox[2] - sbox[0]) / (sbox[3] - sbox[1]):.3f}")auto=False: 600x400 -> 640x640, scale 1.0667, pad left/top 0/106
box [168, 17, 423, 326] -> [179.2, 124.1, 451.2, 453.7] -> back [168.0, 17.0, 423.0, 326.0]
auto=True : 600x400 -> 640x448, scale 1.0667, pad left/top 0/10
box [168, 17, 423, 326] -> [179.2, 28.1, 451.2, 357.7] -> back [168.0, 17.0, 423.0, 326.0]
pad pixel value: [114, 114, 114]
stretched instead: box aspect w/h 0.825 -> 0.550
The round trip is exact in both modes. The square letterbox wastes pixels on padding; the stride-aligned one makes a 640 x 448 input with only 21 padded rows, about 30 % less computation for the same detail. Stretching to 640 x 640 instead would turn the cup's aspect ratio from 0.825 into 0.550, a shape the detector never saw in training if it was trained with letterboxes. The usual bugs here are forgetting the inverse (boxes drawn on the original image land 106 pixels too low) and mixing the padding of one image with the scale of another in a batch.
Affine transforms: rotate, scale, shift, flip
An affine transform maps to with a matrix: it keeps straight lines and parallel lines. Rotation by (counter-clockwise on screen) with scale about a centre , as cv2.getRotationMatrix2D builds it, is
cv2.warpAffine applies it by inverse mapping and interpolation, like a resize. Boxes are the problem: a rotated box is no longer axis-aligned, and the best you can do from the box alone is the box around its four rotated corners.
import numpy as np
import cv2
cv2.setLogLevel(0)
h, w = 200, 300
cx, cy, angle, scale = w / 2, h / 2, 30, 1.0
M = cv2.getRotationMatrix2D((cx, cy), angle, scale)
a, b = scale * np.cos(np.deg2rad(angle)), scale * np.sin(np.deg2rad(angle))
M_ours = np.array([[a, b, (1 - a) * cx - b * cy], [-b, a, b * cx + (1 - a) * cy]])
print("getRotationMatrix2D:"); print(M.round(3))
print("same as the formula:", np.allclose(M, M_ours))
mask = np.zeros((h, w), np.uint8); mask[60:120, 100:200] = 1 # an object: box [100, 60, 200, 120]
box = [100, 60, 200, 120]
rot = cv2.warpAffine(mask, M, (w, h), flags=cv2.INTER_NEAREST) # masks: nearest neighbour
corners = np.array([[100, 60], [200, 60], [200, 120], [100, 120]], np.float64)
new = cv2.transform(corners[None], M)[0]
enc = [new[:, 0].min(), new[:, 1].min(), new[:, 0].max(), new[:, 1].max()]
ys, xs = np.nonzero(rot)
tight = [int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1]
print("corners after rotation:", new.round(1).tolist())
print("box from the 4 corners:", np.round(enc, 1).tolist(), "| tight box of the rotated mask:", tight)
area = lambda b: (b[2] - b[0]) * (b[3] - b[1])
print(f"object area {int(rot.sum())} px, enclosing box area {area(enc):.0f} px ({area(enc) / rot.sum():.2f}x)")
flipped = cv2.flip(mask, 1) # 1 = horizontal flip
ys, xs = np.nonzero(flipped)
print("horizontal flip: box", [w - box[2], box[1], w - box[0], box[3]], "| from the flipped mask", [int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1])getRotationMatrix2D:
[[ 0.866 0.5 -29.904]
[ -0.5 0.866 88.397]]
same as the formula: True
corners after rotation: [[86.7, 90.4], [173.3, 40.4], [203.3, 92.3], [116.7, 142.3]]
box from the 4 corners: [86.7, 40.4, 203.3, 142.3] | tight box of the rotated mask: [87, 41, 203, 143]
object area 5999 px, enclosing box area 11889 px (1.98x)
horizontal flip: box [100, 60, 200, 120] | from the flipped mask [100, 60, 200, 120]
The formula reproduces OpenCV's matrix. For a rectangle the corner-based box is correct (it matches the tight box of the rotated mask to rounding), but it is 1.98 times the object's area: a 30-degree rotation doubles the background inside the box, and IoU-based matching and box regression suffer. For other shapes (a person, a round cup) the box around the rotated box is looser than the box around the rotated object, so rotation augmentation for detection should transform the masks or polygons when they exist, and keep angles small when they do not. A horizontal flip maps , so [x1, y1, x2, y2] becomes [W - x2, y1, W - x1, y2] (with exclusive coordinates there is no ); this box was centred, so it stayed put. Flips are label-preserving for most objects, but not for text, digits, or "left hand" versus "right hand" classes.
Perspective transforms and homographies
A camera looking at a plane (a document, a road, a football pitch) at an angle sees it through a homography: a matrix acting on homogeneous coordinates,
It keeps straight lines straight, but not parallel lines, ratios of lengths or midpoints. has 8 degrees of freedom (it is defined up to scale), so 4 point correspondences determine it. Each correspondence gives two linear equations in the 9 entries of ; stacking them gives , solved by the singular vector of with the smallest singular value (the direct linear transform, DLT). See perspective rendering for the projection side and SVD for the solver.
import numpy as np
import cv2
cv2.setLogLevel(0)
np.set_printoptions(suppress=True)
src = np.float32([[40, 30], [260, 60], [240, 190], [20, 170]]) # a tilted page, corners clockwise
dst = np.float32([[0, 0], [200, 0], [200, 140], [0, 140]]) # where they should go
H_cv = cv2.getPerspectiveTransform(src, dst)
def homography_dlt(src, dst):
A = []
for (x, y), (u, v) in zip(src, dst):
A.append([-x, -y, -1, 0, 0, 0, u * x, u * y, u])
A.append([0, 0, 0, -x, -y, -1, v * x, v * y, v])
_, _, Vt = np.linalg.svd(np.array(A, np.float64))
H = Vt[-1].reshape(3, 3) # null vector of A
return H / H[2, 2]
H = homography_dlt(src, dst)
print("cv2.getPerspectiveTransform:"); print(H_cv.round(4))
print("DLT from scratch, max difference:", f"{np.abs(H - H_cv).max():.2e}")
def apply(H, pts):
p = np.c_[pts, np.ones(len(pts))] @ H.T
return p[:, :2] / p[:, 2:]
print("corners map to:", (apply(H, src).round(3) + 0.0).tolist())
mid = src.mean(0)
print("centroid of the quad", mid.round(1).tolist(), "->", apply(H, mid[None]).round(1).tolist()[0], "(not the rectangle centre [100, 70])")
diag = cv2.perspectiveTransform(np.float32([[[40, 30], [140, 110], [240, 190]]]), H_cv)[0]
print("three points on a diagonal stay on a line:", [[round(float(v), 2) + 0.0 for v in p] for p in diag])
img = np.full((220, 300), 40, np.uint8)
cv2.fillPoly(img, [src.astype(np.int32)], 200) # draw the page
flat = cv2.warpPerspective(img, H_cv, (200, 140))
print("rectified page: mean", round(float(flat.mean()), 1), "| share of bright pixels", round(float((flat > 120).mean()), 3))cv2.getPerspectiveTransform:
[[ 0.8165 0.1166 -36.1598]
[ -0.1309 0.9597 -23.5558]
[ -0.0003 -0.0001 1. ]]
DLT from scratch, max difference: 4.75e-11
corners map to: [[0.0, 0.0], [200.0, 0.0], [200.0, 140.0], [0.0, 140.0]]
centroid of the quad [140.0, 112.5] -> [96.4, 69.8] (not the rectangle centre [100, 70])
three points on a diagonal stay on a line: [[0.0, 0.0], [96.03, 67.22], [200.0, 140.0]]
rectified page: mean 199.8 | share of bright pixels 1.0
The 9-unknown SVD solution matches OpenCV's 8-equation solver to about , and the four corners land exactly on the rectangle. The two non-zero entries in the bottom row of make it a perspective rather than an affine map, and they are why the centroid of the quadrilateral does not go to the centre of the rectangle, while three collinear points stay collinear (the middle point lands on the rectangle's diagonal). The rectified image is all page (the whole output is bright), the basis of every document scanner app: find four corners, compute , warp. With more than four noisy correspondences (matched features), cv2.findHomography solves the over-determined system and rejects outliers with RANSAC; classical features does that to recover a known rotation.
Pitfalls
(width, height)versus(rows, cols).cv2.resize(img, (w, h))andwarpAffine(..., (w, h))take width first;img.shapeis(h, w).- Interpolating labels. Masks and class-id maps must be resized and warped with nearest neighbour; bilinear invents class ids between two classes.
- Half-pixel shifts. Different libraries and flags (
INTER_NEARESTversusINTER_NEAREST_EXACT,align_cornersin PyTorch) map pixel centres differently. Use the same resize in training and serving. - Shrinking without a low-pass filter. Nearest or bilinear downsampling by large factors aliases; use
INTER_AREAor blur first. - Forgetting the inverse. Predictions on a letterboxed or cropped input must be mapped back with the same scale and padding before they are drawn, evaluated or stored.
- Rotating boxes. The box around rotated corners is loose; transform masks or polygons when you have them.
- Clipping. After a crop, shift or rotation, clip boxes to the image and drop the ones that became too small or mostly cut off.
Practice
- You resize a 640-pixel-wide image to 416 pixels with the half-pixel convention. Which input does output pixel 0 sample, and which does output pixel 415?
Answer
and . Both ends sit symmetrically inside the image; the naive mapping would give 0 and 638.46, shifted left.
- A detector returns
[200.0, 150.0, 300.0, 330.0]on a letterboxed 640 x 640 input made from a 1280 x 720 frame. Map it back to the frame.
Answer
; the resized frame is 640 x 360, padded by rows at the top. Back: , , , : [400, 20, 600, 380].
- Flip the box
[10, 20, 50, 80]horizontally in a 200-pixel-wide image.
Answer
[200 - 50, 20, 200 - 10, 80] = [150, 20, 190, 80]. Same width (40), mirrored position.
- Why does a homography need four point pairs, and an affine transform three?
Answer
Each pair gives two equations. An affine map has 6 unknowns (a matrix): three pairs. A homography has 9 entries but is only defined up to scale, so 8 unknowns: four pairs (no three of them collinear).
Test yourself
Which interpolation should be used to resize a segmentation mask of class ids?
- Bilinear
- Bicubic
- Nearest neighbour
- Area
Stripes of period 4.4 pixels were shrunk 4 times. Which method left the least fake pattern?
- Every 4th pixel
- INTER_NEAREST
- INTER_LINEAR
- A Gaussian blur with before subsampling
A 600 x 400 image is letterboxed to 640 x 640 with scale 1.0667 and 106 rows of padding at the top. A predicted box has . What is in the original image?
- 215.6
- 116.3
- 124
- 230
What does a homography preserve?
- Parallel lines
- Straight lines
- Midpoints of segments
- Areas
Rotating an object's box by 30 degrees and taking the box around the rotated corners gave 1.98 times the object's area. What follows for detection augmentation?
- Rotation should never be used
- Rotated boxes are loose; transform masks or polygons when available and keep angles small otherwise
- The box must be shrunk by half
- IoU is unaffected