Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 54 ยท Geometric Transformations

Translation, Rotation and Affine Transforms

Move, rotate and scale images with cv2.warpAffine and getRotationMatrix2D, read the 2x3 matrix, understand inverse mapping, and apply matrices to coordinates in NumPy.

Flipping and 90-degree turns are exact, but real pictures are rarely that tidy. A scanned page is slightly tilted, a logo must be nudged ten pixels to the right, a training image should be rotated by a random few degrees to teach a model robustness. All of these are affine transforms: operations that keep straight lines straight and parallel lines parallel, and that can combine moving, rotating, scaling and shearing.

OpenCV does every one of them with a single function, cv2.warpAffine, driven by a small 2 by 3 matrix. In this lesson you will read that matrix, build one for rotation with cv2.getRotationMatrix2D, see why the warp works backwards from the output, and then apply matrices to coordinates and to a tiny image in NumPy. The cv2 calls are shown read-only, and the NumPy stand-ins run live. If you need to refresh the simpler cases, see Resizing, Cropping and Flipping.

The 2 by 3 matrix

An affine transform maps a point (x, y) to a new point (x', y') using six numbers:

TEXT
x' = a*x + b*y + tx
y' = c*x + d*y + ty

OpenCV stores them as a 2 by 3 matrix M = [[a, b, tx], [c, d, ty]]. The left 2 by 2 block (a, b, c, d) holds rotation, scale and shear. The last column (tx, ty) is the translation. In homogeneous form you can think of a third row [0, 0, 1], which is why a 3 by 3 matrix appears when we reach Perspective Transforms and Document Scanning.

What the six numbers do

Translation [[1, 0, tx], [0, 1, ty]] slides the image.
Scale [[sx, 0, 0], [0, sy, 0]] grows or shrinks.
Rotation Cosines and sines in the left block.
Shear Off-diagonal terms slant the image.

One function, warpAffine, applies any of them.

1 / 2

Translation and the basic call

To slide an image 40 pixels right and 15 pixels down, build the matrix with tx = 40, ty = 15. The matrix must be float32 or float64.

Python
import cv2
import numpy as np

img = cv2.imread("photo.jpg")
h, w = img.shape[:2]

M = np.float32([[1, 0, 40],
                [0, 1, 15]])

shifted = cv2.warpAffine(img, M, (w, h))

The call is cv2.warpAffine(src, M, dsize, flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=0). As with resize, dsize is (width, height). Pixels that move off the output canvas disappear, and newly exposed areas are filled according to borderMode and borderValue (black by default).

Rotation with getRotationMatrix2D

Writing a rotation by hand means getting the center right: rotating about the origin (the top-left corner) throws the picture off-screen. getRotationMatrix2D does the bookkeeping for rotation about any center.

Python
center = (w / 2, h / 2)
M = cv2.getRotationMatrix2D(center, 30, 1.0)     # center, angle in degrees, scale
rotated = cv2.warpAffine(img, M, (w, h))

Two conventions to remember:

  • A positive angle rotates counterclockwise (as you look at the picture, with the origin at the top-left).
  • The matrix has the form [[ฮฑ, ฮฒ, tx], [-ฮฒ, ฮฑ, ty]], with ฮฑ = scale * cos(angle) and ฮฒ = scale * sin(angle). The translation column is chosen so that the center stays where it is.
Python Build the rotation matrix yourself

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The point to the right of the center ends up directly above it. Since the image's y axis points down, "above" means a smaller y, which is a counterclockwise quarter turn on screen. That agrees with the positive-angle rule. (This stand-in follows the documented matrix form; real getRotationMatrix2D returns the same numbers as a float64 array.)

Applying a matrix to coordinates

Before warping pixels, it helps to see the matrix act on plain points. Append a 1 to each point to make (x, y, 1) and multiply by M. With NumPy you can transform a whole list of points at once.

Python Transform the corners of an image

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Transforming the four corners tells you where the whole image ends up. After a rotation, for example, the corners may land at negative coordinates, which is why a rotated image can lose its corners when you keep the old canvas size. To keep everything you can compute the bounding box of the transformed corners, enlarge dsize to that box, and add the box's offset to the matrix translation.

Inverse mapping: why warps do not leave holes

A forward approach would take each input pixel, compute where it lands, and write it there. When the transform enlarges or rotates the picture, some output pixels never get written, leaving little holes. So warpAffine works the other way around: for each output pixel (x', y'), it computes the matching source position with the inverse matrix, then samples the input there (using the interpolation flag).

By default OpenCV treats M as the forward transform (input to output) and inverts it internally. Pass flags=cv2.INTER_LINEAR | cv2.WARP_INVERSE_MAP if your matrix already goes from output to input. cv2.invertAffineTransform(M) returns the inverse if you need it yourself.

Python A warpAffine stand-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the output of the shifted image: the part that moved past the right or bottom edge is cut off, and the exposed area at the top-left is the fill value. The mirror matrix has -1 in the x scale and 8 as translation, because mirroring a 9-pixel-wide image maps column x to 8 - x.

Combining transforms

Because each transform is a matrix, you can chain them by multiplying their 3 by 3 forms. Order matters: "rotate, then move" differs from "move, then rotate". A common recipe for augmentation is: translate the center to the origin, rotate and scale, translate back and then add a small random shift. getRotationMatrix2D already includes the first three steps. Add the extra shift by changing M[0, 2] and M[1, 2].

Python
M = cv2.getRotationMatrix2D((w / 2, h / 2), angle, 1.0)
M[0, 2] += dx
M[1, 2] += dy
out = cv2.warpAffine(img, M, (w, h), borderMode=cv2.BORDER_REFLECT)

BORDER_REFLECT mirrors the image into the empty corners, which often gives better training data than black wedges. If your transform involves a vanishing point (railway tracks that converge) a 2 by 3 matrix is not enough; the next lesson uses a 3 by 3 perspective matrix instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What do the third column values tx and ty of a 2x3 affine matrix mean?

    The left 2x2 block holds rotation, scale and shear. The last column is the translation added after that linear part.
  2. 2. Which rotation does cv2.getRotationMatrix2D(center, 30, 1.0) describe?

    A positive angle rotates counterclockwise, and the matrix keeps center fixed. The scale argument (1.0 here) would be the enlargement.
  3. 3. Why does warpAffine map each output pixel back to the input (inverse mapping)?

    Walking over the output grid guarantees every output pixel is assigned a value, sampled from the source position the inverse transform gives.
  4. 4. What is dsize in cv2.warpAffine(img, M, dsize)?

    As with cv2.resize, dsize is (width, height), the reverse of the order in img.shape.

Summary

  • An affine transform is a 2 by 3 matrix: the left 2 by 2 block rotates, scales and shears; the last column translates. Lines stay straight and parallel lines stay parallel.
  • cv2.warpAffine(img, M, (width, height)) applies it; borderMode and borderValue fill the exposed areas.
  • cv2.getRotationMatrix2D(center, angle, scale) builds a rotation about any center; positive angles turn counterclockwise.
  • Applying M to points means appending a 1 to each point and multiplying; transforming the four corners shows where the image will land and how big the canvas must be.
  • Warps use inverse mapping so the output has no holes; WARP_INVERSE_MAP tells OpenCV your matrix already maps output to input.

Next up: correct a skewed photo with a perspective matrix in Perspective Transforms and Document Scanning.