使得image和xml按着相同的角度进行翻转,可以在目标识别中针对小样本进行一定的数据增强操作
import os
import numpy as np
import cv2
import math
import xml.etree.ElementTree as ET
from PIL import Image
# 按角度翻转图片
def rotate_img(src, angle, scale=1):
width = src.shape[1] # 原始图像的宽
height = src.shape[0] # 原始图像的高
# 角度变弧度
re_angle = np.deg2rad(angle)
# 计算新图片的高度和宽度
new_width = (abs(np.sin(re_angle) * height) + abs(np.cos(re_angle) * width)) * scale
new_height = (abs(np.cos(re_angle) * height) + abs(np.sin(re_angle) * width)) * scale
rotate_matrix = cv2.getRotationMatrix2D((new_width * 0.5, new_height * 0.5), angle, scale)
rotate_move = np.dot(rotate_matrix, np.array([(new_width - width) * 0.5, (new_height - height) * 0.5, 0]))
# update translation
rotate_matrix[0, 2] += rotate_move[0]
rotate_matrix[1, 2] += rotate_move[1]
dst = cv2.warpAffine(img, rotate_matrix, (int(math.ceil(new