TExcelTAD
Home › Computer Vision: Images to Detection, Segmentation & Tracking › Resizing, Cropping and Geometric Transforms

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 h×wh \times w image to h′×w′h' \times w', 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 x′x' has its centre at x′+0.5x' + 0.5, which in input units is (x′+0.5) w/w′(x' + 0.5)\, w / w', so the input index is

x=(x′+0.5) ww′−0.5x = (x' + 0.5)\,\frac{w}{w'} - 0.5

This half-pixel convention keeps the image centred: output and input pixel centres line up geometrically. The naive x=x′⋅w/w′x = x' \cdot w / w' 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, (1−a)(1−b)I00+a(1−b)I01+(1−a)b I10+ab I11(1 - a)(1 - b) I_{00} + a(1 - b) I_{01} + (1 - a) b\, I_{10} + a b\, I_{11} with fractional parts a,ba, b;
  • 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.
python · try it yourself
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 (1.5)(0.5)−0.5=0.25(1.5)(0.5) - 0.5 = 0.25, 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 (−10.5-10.5 and 255.3255.3): clip before converting back to uint8, and never use it on masks. Two traps hide in the downsampling line. INTER_NEAREST picks input ⌊x′w/w′⌋\lfloor x' w / w' \rfloor (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 ss lowers the Nyquist limit from 0.5 to 0.5/s0.5/s 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.

python · try it yourself
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 1/4.4≈0.2271/4.4 \approx 0.227 cycles per pixel; after keeping every 4th pixel that is 0.909 cycles per sample, which aliases to ∣0.909−1∣=0.091\lvert 0.909 - 1 \rvert = 0.091: 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 σ=2\sigma = 2 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 (−x1,−y1)(-x_1, -y_1) (and must be clipped to the crop). A letterbox scales the image by r=min⁡(S/h,S/w)r = \min(S/h, S/w) to fit an S×SS \times S square without distortion and pads the rest with a constant grey (114 in YOLO's convention). A box transforms as b′=r b+(px,py,px,py)b' = r\,b + (p_x, p_y, p_x, p_y) for padding px,pyp_x, p_y on the left and top, and the detector's predictions come back to the original image with the inverse, b=(b′−p)/rb = (b' - p)/r. 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.

original 600 x 400 box [168, 17, 423, 326] x 1.0667 pad: 106 rows pad 107 rows letterbox 640 x 640 r = 1.0667 p = (0, 106, 0, 106) forward: b' = r b + p back: b = (b' - p) / r pad value 114 (grey)
python · try it yourself
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 640×213640 \times 213 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 (x,y)(x, y) to M (x,y,1)TM \, (x, y, 1)^{\mathsf T} with a 2×32 \times 3 matrix: it keeps straight lines and parallel lines. Rotation by θ\theta (counter-clockwise on screen) with scale ss about a centre (cx,cy)(c_x, c_y), as cv2.getRotationMatrix2D builds it, is

M=[αβ(1−α) cx−β cy−βαβ cx+(1−α) cy],α=scos⁡θ,β=ssin⁡θM = \begin{bmatrix} \alpha & \beta & (1 - \alpha)\,c_x - \beta\,c_y \\ -\beta & \alpha & \beta\,c_x + (1 - \alpha)\,c_y \end{bmatrix}, \qquad \alpha = s \cos\theta, \quad \beta = s \sin\theta

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.

python · try it yourself
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 x→W−xx \to W - x, so [x1, y1, x2, y2] becomes [W - x2, y1, W - x1, y2] (with exclusive coordinates there is no −1-1); 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 3×33 \times 3 matrix HH acting on homogeneous coordinates,

[u′v′w′]=H[xy1],(u,v)=(u′w′, v′w′)\begin{bmatrix} u' \\ v' \\ w' \end{bmatrix} = H \begin{bmatrix} x \\ y \\ 1 \end{bmatrix}, \qquad (u, v) = \left(\frac{u'}{w'},\ \frac{v'}{w'}\right)

It keeps straight lines straight, but not parallel lines, ratios of lengths or midpoints. HH has 8 degrees of freedom (it is defined up to scale), so 4 point correspondences determine it. Each correspondence (x,y)→(u,v)(x, y) \to (u, v) gives two linear equations in the 9 entries of HH; stacking them gives Ah=0A h = 0, solved by the singular vector of AA with the smallest singular value (the direct linear transform, DLT). See perspective rendering for the projection side and SVD for the solver.

python · try it yourself
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 10−1110^{-11}, and the four corners land exactly on the rectangle. The two non-zero entries in the bottom row of HH 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 HH, 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)) and warpAffine(..., (w, h)) take width first; img.shape is (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_NEAREST versus INTER_NEAREST_EXACT, align_corners in 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_AREA or 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

  1. You resize a 640-pixel-wide image to 416 pixels with the half-pixel convention. Which input xx does output pixel 0 sample, and which does output pixel 415?
Answer

x=(0+0.5)⋅640/416−0.5≈0.269x = (0 + 0.5) \cdot 640/416 - 0.5 \approx 0.269 and x=415.5⋅640/416−0.5≈638.73x = 415.5 \cdot 640/416 - 0.5 \approx 638.73. Both ends sit symmetrically inside the image; the naive mapping x′⋅640/416x' \cdot 640/416 would give 0 and 638.46, shifted left.

  1. 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

r=min⁡(640/720,640/1280)=0.5r = \min(640/720, 640/1280) = 0.5; the resized frame is 640 x 360, padded by (640−360)/2=140(640 - 360)/2 = 140 rows at the top. Back: x=(200−0)/0.5=400x = (200 - 0)/0.5 = 400, y=(150−140)/0.5=20y = (150 - 140)/0.5 = 20, x2=600x_2 = 600, y2=(330−140)/0.5=380y_2 = (330 - 140)/0.5 = 380: [400, 20, 600, 380].

  1. 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.

  1. 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 2×32 \times 3 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?

  1. Bilinear
  2. Bicubic
  3. Nearest neighbour
  4. Area

Stripes of period 4.4 pixels were shrunk 4 times. Which method left the least fake pattern?

  1. Every 4th pixel
  2. INTER_NEAREST
  3. INTER_LINEAR
  4. A Gaussian blur with σ=2\sigma = 2 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 y1=230y_1 = 230. What is y1y_1 in the original image?

  1. 215.6
  2. 116.3
  3. 124
  4. 230

What does a homography preserve?

  1. Parallel lines
  2. Straight lines
  3. Midpoints of segments
  4. 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?

  1. Rotation should never be used
  2. Rotated boxes are loose; transform masks or polygons when available and keep angles small otherwise
  3. The box must be shrunk by half
  4. IoU is unaffected