Image Rotation: Working Backwards From Each Pixel

Computer VisionMedium+15 XP+15

Image Rotation: Working Backwards From Each Pixel

Rotating an image sounds like it should work forwards — take each pixel, work out where it lands, put it there. It doesn't: rotated positions are fractional, several source pixels can round to the same destination, and others get nothing, leaving holes.

Every real implementation runs backwards instead. For each output pixel, ask where it came from. Every output gets exactly one answer, and no holes are possible.

Task: write rotate_nearest(image, degrees) returning a rotated grid of the same size.

With the centre at cy = (rows - 1) / 2, cx = (cols - 1) / 2, and θ the angle in radians, for each output pixel (r, c):

  1. Offset from the centre: dx = c - cx, dy = r - cy.
  2. Rotate backwards to find the source offset:
sx=cos⁡θ⋅dx+sin⁡θ⋅dy,sy=−sin⁡θ⋅dx+cos⁡θ⋅dysx = \cos\theta \cdot dx + \sin\theta \cdot dy, \qquad sy = -\sin\theta \cdot dx + \cos\theta \cdot dysx=cosθ⋅dx+sinθ⋅dy,sy=−sinθ⋅dx+cosθ⋅dy
  1. Add the centre back and round to the nearest pixel: src_c = round(sx + cx), src_r = round(sy + cy).
  2. If that pixel is inside the image, copy it. If not, write 0.
  • degrees is in degrees — convert with math.radians.
  • Use Python's built-in round().
  • Positive angles rotate the image counter-clockwise.
  • The corners of a rotated square fall outside the frame, so corner outputs become 0 — that's the black triangles you see on any naively rotated photo.

Note the sign pattern in step 2: it's the rotation matrix for -θ, not θ. Using the forward matrix produces an image rotated the wrong way, which is an easy bug to ship because the output still looks like a rotation.

"Nearest neighbour" is the crudest resampling there is — it just grabs whichever pixel is closest, so diagonal edges come out visibly jagged. Bilinear interpolation on those same fractional coordinates is the usual upgrade.

Examples

image = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
degrees = 90
returns [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
image = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
degrees = 180
returns [[9, 8, 7], [6, 5, 4], [3, 2, 1]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run