在图像处理中有时候需要对图像进行旋转,如果要实现任意角度的旋转,则涉及线性变换的矩阵运算,比较复杂。有时候只是想实现简单的向左、向右旋转,感觉就是跟矩阵转置差不多的操作,用for循环重新排列像素点也能实现。但是也不用这么复杂,numpy提供的rot90()
函数就能实现。
在目标检测场景下,图像旋转还涉及到标注框坐标的变化,那么还需要多做一步,就是计算旋转后标注框的坐标,下面的函数就实现了这样的功能。
import numpy as np
def rot90(image, points, times: int):
"""
逆时针90°旋转图像times次,并计算图像image中的坐标点points在旋转后的图像中的位置坐标.
Args:
image: 图像数组
points: [(x, y), ...],原图像中的坐标点集合
times: 旋转次数
"""
if times % 4 == 0: # 旋转4的倍数次,相当于不旋转
return image, points
else:
times = times % 4
image = np.rot90(image, times, (0, 1)) # 通过numpy实现图像旋转
h, w = image.shape[: 2]
new_pts = []
for j, i in points:
if times == 1:
new_pts.append([i, w - j - 1])
elif times == 2:
new_pts.append([w - j - 1, h - i - 1])
else:
new_pts.append([h - i - 1, j])
return image, new_pts