Problems
Loading...
1 / 1

Image Rotation (Nearest Neighbor)

Computer Vision
Medium

Rotating an image by an arbitrary angle requires mapping each output pixel back to its source location in the input. Nearest neighbor interpolation selects the closest input pixel, producing a fast (though aliased) result.

Given a 2D image and an angle in degrees (counterclockwise), rotate the image around its center using nearest neighbor interpolation. Pixels that map outside the input bounds are filled with 0.

Algorithm

The center of the image is:

cy=H12cx=W12cy = \frac{H - 1}{2} \qquad cx = \frac{W - 1}{2}

For each output pixel (i, j), compute the offset from center: dy = i - cy, dx = j - cx. Apply the inverse rotation to find the source pixel:

src_y=cy+dycosθ+dxsinθsrc\_y = cy + dy \cos\theta + dx \sin\theta src_x=cxdysinθ+dxcosθsrc\_x = cx - dy \sin\theta + dx \cos\theta

where theta is the angle in radians. Round src_y and src_x to the nearest integer. If the result is within bounds, copy that pixel; otherwise output 0.

Loading visualization...

Examples

Input:

image = [[1,2,3],[4,5,6],[7,8,9]], angle_degrees = 180

Output:

[[9,8,7],[6,5,4],[3,2,1]]

Rotating 180 degrees flips the image both horizontally and vertically. The center pixel (5) stays in place.

Input:

image = [[1,2,3],[4,5,6],[7,8,9]], angle_degrees = 0

Output:

[[1,2,3],[4,5,6],[7,8,9]]

No rotation. The image is returned unchanged.

Hint 1

Convert degrees to radians using math.radians(). The inverse rotation formulas use cos and sin of the angle directly.

Hint 2

Use Python's built-in round() to snap to the nearest integer pixel. Check bounds (0 <= sy < H and 0 <= sx < W) before accessing the source image.

Requirements

  • Rotate around the image center, not the top-left corner
  • Use inverse mapping: for each output pixel, find the source pixel
  • Apply round() for nearest neighbor selection
  • Fill out-of-bounds pixels with 0

Constraints

  • Image has at least one pixel
  • angle_degrees can be any number (positive = counterclockwise)
  • Output has the same dimensions as the input
  • Out-of-bounds pixels are filled with 0
  • Time limit: 300 ms
Try Similar Problems