Skip to content
DeepForgeby svx
All problems
HardComputer Visioncv-080

Rotate Arbitrary Angle

Problem

Rotate a 2D image by an arbitrary angle using nearest-neighbor sampling.

For each output pixel (i, j) let dy = i - (H - 1) / 2 and dx = j - (W - 1) / 2, then sample the input at round((H - 1) / 2 + dy * cos(a) + dx * sin(a)) and round((W - 1) / 2 - dy * sin(a) + dx * cos(a)), where a = radians(angle). Out-of-bounds samples become 0 and the output keeps the original shape.

Hint

Use the inverse rotation to map each output pixel back to a source pixel.

Test cases

case 1
in: [[[1,2,3],[4,5,6],[7,8,9]],0]
expected: [[1,2,3],[4,5,6],[7,8,9]]
case 2
in: [[[1,2,3],[4,5,6],[7,8,9]],180]
expected: [[9,8,7],[6,5,4],[3,2,1]]
case 3
in: [[[1,2,3],[4,5,6],[7,8,9]],90]
expected: [[3,6,9],[2,5,8],[1,4,7]]
case 4
in: [[[1,2,3],[4,5,6]],90]
expected: [[3,3,0],[1,1,0]]
Starter codePython
def rotate_nearest(image, angle):
    # Your code here
    pass

4 test cases · run your code against them in the editor