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.
The center of the image is:
cy=2H−1cx=2W−1For 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_x=cx−dysinθ+dxcosθ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.
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.
Convert degrees to radians using math.radians(). The inverse rotation formulas use cos and sin of the angle directly.
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.
Sign in to take notes on this problem
Accepts: array
Accepts: number
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.
The center of the image is:
cy=2H−1cx=2W−1For 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_x=cx−dysinθ+dxcosθ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.
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.
Convert degrees to radians using math.radians(). The inverse rotation formulas use cos and sin of the angle directly.
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.
Sign in to take notes on this problem
Accepts: array
Accepts: number