先给出代码:
def rotate_image(img, angle):
radians = math.radians(angle)
height, width = img.shape[:2]
rotated_img = np.zeros_like(img)
center_x, center_y = width / 2, height / 2
for y in range(height):
for x in range(width):
new_x = (x - center_x) * math.cos(radians) - (y - center_y) * math.sin(radians) + center_x
new_y = (x - center_x) * math.sin(radians) + (y - center_y) * math.cos(radians) + center_y
if 0 <= new_x < width and 0 <= new_y < height:
rotated_img[int(new_y), int(new_x)] = img[y, x]
return rotated_img
其中,值得注意的是
new_x = (x - center_x) * math.cos(radians) - (y - center_y) * math.sin(radians) + center_x
new_y = (x - center_x) * math.sin(radians) + (y - center_y) * math.cos(radians) + center_y
这里用到了一个旋转公式,推导记录一下。
其中v的坐标为(x,y),v'的坐标为(x',y')