CV Geometric Transformations

Geometric transformations move pixels to new positions. Resizing, rotating, shifting, flipping, and straightening a tilted document all belong to this family. Vision pipelines use these tools to prepare images, correct camera angles, and create extra training examples.

How a Transformation Works

Every pixel at position (x, y) travels to a new position (x', y'). A small matrix describes the movement. Software applies the matrix to each pixel and fills the gaps with interpolation.

Source image            Transformation matrix           Result
(x, y)  ---------->  [ a  b  tx ]  ---------->  (x', y')
                     [ c  d  ty ]

Think of a photo printed on a rubber sheet. Pushing, twisting, or stretching the sheet moves every dot on it in a predictable way.

Resizing

Resizing changes the width and height. Shrinking discards detail, and enlarging invents new pixels by interpolation.

import cv2

img = cv2.imread("photo.jpg")
small = cv2.resize(img, (320, 240), interpolation=cv2.INTER_AREA)
large = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)

Choosing an Interpolation Method

Method          Best for             Speed    Quality
--------------  -------------------  -------  ---------
INTER_NEAREST   masks, label maps    fastest  blocky
INTER_LINEAR    general use          fast     good
INTER_CUBIC     enlarging photos     medium   smoother
INTER_AREA      shrinking photos     medium   cleanest

Use nearest neighbor for segmentation masks, because blending class labels creates invalid values.

Translation, Rotation, and Flipping

Translation

Translation slides the image by tx pixels sideways and ty pixels vertically.

import numpy as np
M = np.float32([[1, 0, 50], [0, 1, 30]])   # right 50, down 30
shifted = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))

Rotation

Rotation spins the image around a center point. OpenCV builds the matrix from an angle and a scale.

h, w = img.shape[:2]
M = cv2.getRotationMatrix2D((w // 2, h // 2), 30, 1.0)
rotated = cv2.warpAffine(img, M, (w, h))

Flipping

mirror = cv2.flip(img, 1)    # left-right
upside = cv2.flip(img, 0)    # top-bottom

Affine Transformations

An affine transformation keeps straight lines straight and parallel lines parallel. It combines shifting, rotating, scaling, and shearing. Three matching point pairs define the transformation.

Original rectangle       Affine result (sheared)
+--------+                  +--------+
|        |       ->        /        /
|        |                /        /
+--------+               +--------+
src = np.float32([[0, 0], [200, 0], [0, 200]])
dst = np.float32([[0, 0], [200, 0], [60, 200]])
M = cv2.getAffineTransform(src, dst)
sheared = cv2.warpAffine(img, M, (300, 200))

Perspective Transformations

A perspective transformation mimics a change of camera viewpoint, so parallel lines may converge. Four point pairs define it. A document photographed at an angle becomes a flat, top-down page after the transformation.

Angled photo of a page           Flat scan
   /----------\                  +----------+
  /            \       ->        |          |
 /______________\                |          |
                                 +----------+
src = np.float32([[120, 80], [520, 60], [580, 400], [60, 420]])
dst = np.float32([[0, 0], [500, 0], [500, 700], [0, 700]])
M = cv2.getPerspectiveTransform(src, dst)
flat = cv2.warpPerspective(img, M, (500, 700))

The source points come from the four corners of the page, often found with contour detection.

Comparing the Transformation Types

Type          Keeps                      Points needed
------------  -------------------------  -------------
Translation   shape and size             1 shift value
Rotation      shape and size             angle + center
Affine        straight, parallel lines   3 point pairs
Perspective   straight lines             4 point pairs

Common Problems

  • Rotation cuts off corners, so enlarge the output canvas when the full image must stay visible
  • Black borders appear where no source pixel exists, so choose a border mode such as reflection when needed
  • Repeated transformations blur the image, so combine steps into one matrix when possible
  • Wrong point order in perspective transforms flips the output, so keep corners in a consistent order

Where These Tools Appear

Document scanners flatten pages. Training pipelines rotate and flip photos to create variety. Panorama tools warp overlapping images into one plane. Medical software aligns scans taken on different days.

Practice Exercise

Photograph a book on a table at an angle. Click its four corners with the mouse, build a perspective matrix, and produce a flat cover image. Rotate the result by 15 degrees and compare the borders under two border modes.

Combining Transformations

Real projects chain several moves. A document pipeline may shrink a photo for faster processing, find the page corners, flatten the page, and rotate it upright. Each step multiplies a matrix with the previous one. Combining matrices into a single warp keeps the image sharp, because pixels get resampled only once.

Resize -> Find corners -> Perspective warp -> Rotate upright -> Clean scan

Working With Coordinates

Image coordinates start at the top-left corner. The x value grows to the right and the y value grows downward. Rotation angles in OpenCV count counterclockwise for positive values. Point arrays for transformations must use float32 numbers, and mixing up the order of x and y causes confusing flips.

Quick Reminders

  • Array shape lists height first, while OpenCV size arguments list width first
  • Use the same point order in the source and target arrays
  • Check the output visually after every new matrix