smartyfy.mrindigi.com

Python Master Course V2 — 162. Image Geometry, Resizing and Coordinate Transforms

Purpose and learning outcomes

Image transforms change both pixels and the coordinate system used to describe them. A perfectly resized image can still train a broken detector if its bounding boxes remain in the original coordinates. You will transform a synthetic rectangle through crop, resize, horizontal flip, and a ninety-degree rotation, updating its box at every stage. The conventions are explicit and testable.

  • Apply crop, resize, flip and rotation operations
  • Track coordinate systems and interpolation effects
  • Transform image labels consistently with pixels

Prerequisites

  • 161: image representation
  • 122: coordinate algebra

Environment and execution

Use a project-specific virtual environment with a currently supported Python 3 release compatible with the packages below. Python 3.11 or 3.12 is a practical starting point. Run shell commands in a terminal, then run the Python blocks in order in one script or notebook kernel. They use only included data and local CPU computation. No account, API key, camera, or external dataset is required. Record the installed package versions with python -m pip freeze when you save your results; a random seed does not guarantee identical numerical behavior across library versions.

python -m venv .venv
# macOS/Linux: source .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1
python -m pip install numpy Pillow

Understand the model and its assumptions

We use edge-coordinate boxes in the form x1, y1, x2, y2, with the right and bottom edges excluded. Width is x2 minus x1, and height is y2 minus y1. This matches NumPy slicing: array[y1:y2, x1:x2]. A one-pixel region has positive width and height of one. Mixing this convention with inclusive last-pixel coordinates causes persistent off-by-one errors.

Cropping translates coordinates by the crop origin and clips them to the retained image. A box with zero remaining width or height should be discarded, not treated as an object with negative area. Resizing multiplies x coordinates by the horizontal scale and y coordinates by the vertical scale. Unequal scales distort shape; use aspect-preserving resizing with padding if shape is important to the task.

A horizontal flip across an image of width W maps the edges to W minus x2 and W minus x1. For a ninety-degree counterclockwise rotation, a source box maps to y1, W minus x2, y2, W minus x1, and image dimensions swap. These formulas apply to continuous edges. Point coordinates defined at pixel centers require a different offset convention, which is why every annotation format should document its geometry.

Interpolation also depends on the data. Bilinear or higher-order filters blend neighboring intensity values and are useful for ordinary photographs. Class masks contain categorical labels, so nearest-neighbor resampling prevents invented class values. In this exercise nearest-neighbor image resizing keeps the synthetic binary rectangle crisp, allowing exact agreement between its transformed pixels and transformed box.

Worked example: build it in stages

Start with a sixteen-by-twelve RGB array and a half-open rectangle. The crop helper verifies bounds before translating the box. The resize, flip, and rotation steps apply formulas in the coordinate frame of their immediate input, not the original image. At the end, derive a box from the nonzero pixels and compare it with the transformed annotation.

import numpy as np
from PIL import Image

def crop_box(box, crop):
    x1, y1, x2, y2 = box
    left, top, right, bottom = crop
    result = (max(x1, left)-left, max(y1, top)-top,
              min(x2, right)-left, min(y2, bottom)-top)
    return result if result[2] > result[0] and result[3] > result[1] else None

def scale_box(box, old_size, new_size):
    sx, sy = new_size[0]/old_size[0], new_size[1]/old_size[1]
    x1, y1, x2, y2 = box
    return (x1*sx, y1*sy, x2*sx, y2*sy)

def flip_box(box, width):
    x1, y1, x2, y2 = box
    return (width-x2, y1, width-x1, y2)

def rotate_ccw_box(box, width):
    x1, y1, x2, y2 = box
    return (y1, width-x2, y2, width-x1)

pixels = np.zeros((12, 16, 3), dtype=np.uint8)
box = (4, 3, 10, 9)
pixels[3:9, 4:10] = [255, 0, 0]
image = Image.fromarray(pixels)
crop = (2, 1, 14, 11)
assert 0 <= crop[0] < crop[2] <= image.width
assert 0 <= crop[1] < crop[3] <= image.height
image = image.crop(crop)
box = crop_box(box, crop)
assert box == (2, 2, 8, 8)
new_size = (24, 20)
box = scale_box(box, image.size, new_size)
image = image.resize(new_size, resample=Image.Resampling.NEAREST)
box = flip_box(box, image.width)
image = image.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
box = rotate_ccw_box(box, image.width)
image = image.transpose(Image.Transpose.ROTATE_90)
mask = np.asarray(image)[:, :, 0] > 0
y, x = np.nonzero(mask)
observed = (int(x.min()), int(y.min()), int(x.max()+1), int(y.max()+1))
print("size:", image.size, "box:", box)
assert np.allclose(box, observed)
assert crop_box((0, 0, 1, 1), crop) is None

What the output means

The final image size is (20, 24), and the transformed box is numerically (4, 4, 16, 16). Some coordinates print as floats because resizing uses scale factors. The pixel-derived box matches the transformed annotation. That exact equality is supported by the chosen integer scaling and right-angle operations; arbitrary rotations and interpolation require tolerances and a more careful annotation policy.

Guided lab and acceptance checks

Change the initial rectangle so that the crop cuts through it. Predict its clipped box before running the code. Then try a crop that removes it entirely and ensure downstream code handles None rather than unpacking a nonexistent object. Add a second rectangle and transform both annotations through the same operation sequence.

Acceptance requires a saved transform sequence, bounds checks after every step, and a visual or pixel-level overlay verification. For noninteger resizes, keep continuous box coordinates until the final consumer explicitly requires rounding. Explain how much object area was lost to cropping; a severely truncated object may need a separate label policy.

Common mistakes and repairs

Do not apply a flip formula using the pre-resize width. Do not mix array row-column ordering with x-y ordering. Avoid rounding after every transform, since rounding errors accumulate. Never resize segmentation labels with bilinear interpolation. Finally, an enclosing axis-aligned box after arbitrary rotation includes background and is not identical to a rotated object polygon.

Questions and answers

Why prefer half-open boxes in this lesson?

They align with Python slices and make width and height simple differences. The convention is not universally required, but consistency is. When importing another annotation format, convert once at the boundary and test one-pixel and edge-touching cases.

Why do image dimensions swap after a right-angle rotation?

A ninety-degree turn maps the original horizontal extent onto the vertical extent and vice versa. The box transformation must use the old width before the image is rotated; using the new width applies the wrong coordinate frame.

Can every augmentation preserve a label?

No. A crop can remove the object, a flip can change a directional symbol, and a rotation can change a digit's identity. Decide which transformations preserve the task's semantics before adding them to a training pipeline.

Why keep box coordinates as floats after resizing?

Continuous edges represent the transformed geometry without repeated rounding loss. Rasterization into pixel indexes is a separate decision that needs an explicit floor, ceiling, or nearest policy depending on whether you need coverage, containment, or a center estimate.

What changes for arbitrary-angle rotation?

Transform all box corners with the same affine mapping as the pixels, then choose whether to retain a rotated polygon or compute an enclosing axis-aligned box. Padding, output expansion, and interpolation all affect the final frame and must be accounted for.

Exercises

1. Verify that two horizontal flips restore a box. 2. Verify that resizing by a factor and its inverse restores continuous coordinates within tolerance. 3. Explain why pixel-perfect restoration is not guaranteed after downsampling and upsampling an image.

Worked solutions and reasoning

Coordinate transforms can be algebraically invertible even when raster resampling discards information. Downsampling merges or removes pixel detail; enlarging later cannot reconstruct the original values. The coordinate test therefore checks geometry separately from image reconstruction.

original = (2.5, 1.5, 7.5, 6.5)
assert flip_box(flip_box(original, 12), 12) == original
scaled = scale_box(original, (12, 10), (18, 15))
restored = scale_box(scaled, (18, 15), (12, 10))
assert np.allclose(original, restored)

Recap

Geometry is a shared contract between pixels and labels. Keep coordinate conventions, scale factors, clipping, and interpolation explicit. Test transformations with small synthetic shapes before trusting a large labeled dataset; an image that looks correct can still carry wrong annotations.

Official references

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.