# 旋转 | |
def _rotate_img_bbox(self, img, bboxes, angle=5, scale=1.): | |
''' | |
参考:https://blog.csdn.net/u014540717/article/details/53301195crop_rate | |
输入: | |
img:图像array,(h,w,c) | |
bboxes:该图像包含的所有boundingboxs,一个list,每个元素为[x_min, y_min, x_max, y_max],要确保是数值 | |
angle:旋转角度 | |
scale:默认1 | |
输出: | |
rot_img:旋转后的图像array | |
rot_bboxes:旋转后的boundingbox坐标list | |
''' | |
#---------------------- 旋转图像 ---------------------- | |
w = img.shape[1] | |
h = img.shape[0] | |
# 角度变弧度 | |
rangle = np.deg2rad(angle) # angle in radians | |
# now calculate new image width and height | |
nw = (abs(np.sin(rangle)*h) + abs(np.cos(rangle)*w))*scale | |
nh = (abs(np.cos(rangle)*h) + abs(np.sin(rangle)*w))*scale | |
# ask OpenCV for the rotation matrix | |
rot_mat = cv2.getRotationMatrix2D((nw*0.5, nh*0.5), angle, scale) | |
# calculate the move from the old center to the new center combined | |
# with the rotation | |
rot_move = np.dot(rot_mat, np.array([(nw-w)*0.5, (nh-h)*0.5,0])) | |
# the move only affects the translation, so update the translation | |
# part of the transform | |
rot_mat[0,2] += rot_move[0] | |
rot_mat[1,2] += rot_move[1] | |
# 仿射变换 | |
rot_img = cv2.warpAffine(img, rot_mat, (int(math.ceil(nw)), int(math.ceil(nh))), flags=cv2.INTER_LANCZOS4) | |
#---------------------- 矫正bbox坐标 ---------------------- | |
# rot_mat是最终的旋转矩阵 | |
# 获取原始bbox的四个中点,然后将这四个点转换到旋转后的坐标系下 | |
rot_bboxes = list() | |
for bbox in bboxes: | |
xmin = bbox[0] | |
ymin = bbox[1] | |
xmax = bbox[2] | |
ymax = bbox[3] | |
point1 = np.dot(rot_mat, np.array([(xmin+xmax)/2, ymin, 1])) | |
point2 = np.dot(rot_mat, np.array([xmax, (ymin+ymax)/2, 1])) | |
point3 = np.dot(rot_mat, np.array([(xmin+xmax)/2, ymax, 1])) | |
point4 = np.dot(rot_mat, np.array([xmin, (ymin+ymax)/2, 1])) | |
# 合并np.array | |
concat = np.vstack((point1, point2, point3, point4)) | |
# 改变array类型 | |
concat = concat.astype(np.int32) | |
# 得到旋转后的坐标 | |
rx, ry, rw, rh = cv2.boundingRect(concat) | |
rx_min = rx | |
ry_min = ry | |
rx_max = rx+rw | |
ry_max = ry+rh | |
# 加入list中 | |
rot_bboxes.append([rx_min, ry_min, rx_max, ry_max]) | |
return rot_img, rot_bboxes |
参考链接:https://github.com/maozezhong/CV_ToolBox/blob/master/DataAugForObjectDetection/DataAugmentForObejctDetection.py