代码
def rotate_im_poly(im, text_polys):
"""
rotate image with 90 / 180 / 270 degre
"""
im_w, im_h = im.shape[1], im.shape[0]
dst_im = im.copy()
dst_polys = []
rand_degree_ratio = np.random.rand()
rand_degree_cnt = 1
if 0.333 < rand_degree_ratio < 0.666:
rand_degree_cnt = 2
elif rand_degree_ratio > 0.666:
rand_degree_cnt = 3
for i in range(rand_degree_cnt):
dst_im = np.rot90(dst_im)
rot_degree = -90 * rand_degree_cnt
rot_angle = rot_degree * math.pi / 180.0
n_poly = text_polys.shape[0]
cx, cy = 0.5 * im_w, 0.5 * im_h
ncx, ncy = 0.5 * dst_im.shape[1], 0.5 * dst_im.shape[0]
for i in range(n_poly):
wordBB = text_polys[i]
poly = []
for j in range(4):
sx, sy = wordBB[j][0], wordBB[j][1]
dx = math.cos(rot_angle) * (sx - cx)\
- math.sin(rot_angle) * (sy - cy) + ncx
dy = math.sin(rot_angle) * (sx - cx)\
+ math.cos(rot_angle) * (sy - cy) + ncy
poly.append([dx, dy])
dst_polys.append(poly)
dst_polys = np.array(dst_polys, dtype=np.float32)
return dst_im, dst_polys
注意
- 这里图片旋转后没有保持原始size,比如(1280,720,3)的图片旋转90度后size变成(720,1280,3),而不是保持原始size然后四周填白
- 代码中计算坐标变换采用的是顺时针计算公式,因此角度rot_degree是乘以-90
- 因为旋转后没有保持原始size,所以计算坐标变换最后+ncx是旋转后图片中心点横坐标,而不是加上旋转前中心点横坐标cx
参考
cv2.getRotationMatrix2D的旋转矩阵的正确形式
图像旋转后的还原图像坐标
图像中一个坐标绕图像中心旋转90度、-90度、180度的新坐标求解