Rotating an image with NumPy

Rotating pixels by hand exposes two classic bugs — an off-by-half centre and holes from forward mapping.

What you'll learn
  • Rotate pixel coordinates about the image centre with a 2×2 matrix
  • Explain why forward mapping leaves holes and inverse mapping does not
  • Find the centre of a pixel grid correctly

rotate_any_matrix.py rotates an image the direct way. For every pixel it shifts coordinates so the centre is the origin, applies a rotation matrix, shifts back, rounds, and writes the value at the new position:

rotation_matrix = np.array([[costheta, sintheta],
                            [-sintheta, costheta]])
center_y, center_x = h / 2, w / 2
...
new_x, new_y = np.dot(rotation_matrix, [x, y])
new_i = int(round(new_y + center_y))  # issue
new_j = int(round(new_x + center_x))
if 0 <= new_i < h and 0 <= new_j < w:
    rotated_matrix[new_i, new_j] = matrix[i, j]

The # issue comment is right, and there are two issues.

A 15×15 image rotated from 0° to 90°. Orange pixels are holes: output pixels that should be filled but that no input pixel landed on. Switch between the script's version, the corrected centre, and inverse mapping.

Issue 1: the centre is half a pixel off

Pixel indices run from 0 to \(h - 1\), so the centre of the grid is \((h-1)/2\), not \(h/2\). For the script’s 3×3 example the centre should be 1, not 1.5. The half-pixel error shifts every pixel, so even a clean 90° rotation goes wrong:

expected (np.rot90)      rotate_any_matrix(m, 90)
[[3 6 9]                 [[0 0 0]
 [2 5 8]                  [3 6 9]
 [1 4 7]]                 [2 5 8]]

A whole row falls off the edge and a row of zeros appears. With center_y, center_x = (h - 1) / 2, (w - 1) / 2 the result matches np.rot90 exactly.

Issue 2: forward mapping leaves holes

Even with the right centre, any angle that is not a multiple of 90° leaves gaps. Each input pixel is sent to one rounded output position, but rotation does not map the integer grid onto itself: some outputs receive two inputs and others none.

Forward mapping empties up to 18% of the pixels at 45°. Inverse mapping leaves none at every angle.

The cure is to turn the loop around. Inverse mapping visits every output pixel, rotates its coordinates backwards (by the transpose of the rotation matrix), and copies whichever input pixel lands there. Every output gets exactly one value. Real libraries go one step further and interpolate between the neighbouring inputs instead of rounding, which is what scipy.ndimage.rotate — the script’s rotate_matrix_effectively — does with spline interpolation; with reshape=False it returns exactly np.rot90’s answer for the 3×3 example.

Try it yourself. Rewrite rotate_any_matrix with inverse mapping and the corrected centre, then vectorise it: build index grids with np.indices, rotate them in one matrix product, and gather with fancy indexing. Time both versions on a 512×512 image.

View source on GitHub →