主要是关于图片旋转以及其上点的变化
我要做的是增加数据,旋转图片形成新数据,那其上目标框发生变化,就要形成新目标框box,就去找原框的四个点进行旋转后得到的点,选择其最大最小x,y,形成新框。自己研究一天考了很多资料,但最后还是选用现有opencv算法进行旋转(真滴快0-0)
虽然结果很完美
#特别慢:每一张图都要全遍历一次,机器直接跑一圈慢了10多分钟。(人都傻了当时)
参考
参考一个做的很好的理论分析到位的博文,讲解了旋转理论和客观性不错的实例。
理论我懂了,但代码在深度学习里就是慢
参考
那么接下来
那么接下来找现成的矩阵变换的0-0
直接使用opencv现有包进行旋转,大神还是多,我是菜鸡
参考
下面展示一些 能运行的代码。
image 格式一定要看呀
angle 旋转度(我做的是逆时针,参考理论的博文可以自己改)
box 目标框的最大最小值[x_min,y_min,x_max,y_max]
这里只是单个的目标框,如果多个,直接for box in boxs:#完事
-*- coding: utf-8 -*-
from numpy import *
from PIL import Image,ImageDraw, ImageFont
from PIL import Image
import cv2
import numpy as np
import math
import matplotlib.pyplot as plt
#我要求的是box旋转后形成新的box_new,如果仅仅是旋转,直接看链接博客#
#box我的数据格式[x_min,y_min,x_max,y_max]#
def rotate_bound(image, angle,box,flag=True):
# grab the dimensions of the image and then determine the
# center
#------------------------------------------------#
#主要还是要看你的读入图片是不是np.array格式,不是一定要转#
#------------------------------------------------#
(h, w) = image.shape[:2]
(cX, cY) = (w // 2, h // 2)
#---------------------------------------------------#
#以下时为了找到旋转后box的的x,y最大最小值,返回box_new#
#----------------------------------------------------#
box_xx = []
box_yy = []
box_new = box
x_min = box[0]
y_min = box[1]
x_max = box[2]
y_max = box[3]
#得到一个旋转后的图具体看链接的讲解
M = cv2.getRotationMatrix2D((cX, cY), angle, 1.0)
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])
# 新的宽,高。当然也可以用其他方法计算新的宽高(链接里有其他计算方法)#
nW = int((h * sin) + (w * cos))
nH = int((h * cos) + (w * sin))
#因为我的数据原因,我做的是逆时针旋转,当然也可正向,计算的公式可以看链接#
angle_new = -math.radians(angle % 360)
for x0,y0 in ((x_min,y_min),(x_min,y_max),(x_max,y_min),(x_max,y_max)):
x = x0 * math.cos(angle_new) - y0 * math.sin(angle_new) + 0.5 * h * math.sin(angle_new) - 0.5 * w * math.cos(angle_new) + 0.5 * nW
y = x0 * math.sin(angle_new) + y0 * math.cos(angle_new) - 0.5 * w * math.sin(angle_new) - 0.5 * h * math.cos(angle_new) + 0.5 * nH
box_xx.append(x)
box_yy.append(y)
box_new[0] = math.floor(min(box_xx))
box_new[2] = math.ceil(max(box_xx))
box_new[1] = math.floor(min(box_yy))
box_new[3] = math.ceil(max(box_yy))
# adjust the rotation matrix to take into account translation
M[0, 2] += (nW / 2) - cX
M[1, 2] += (nH / 2) - cY
#cv2.warpAffine(image, M, (nW, nH)) 还是得注意数据格式,#
# 记得和接下来要求的格式相同就行#
if flag:
return cv2.warpAffine(image, M, (nW, nH)),box_new
else:
return box_new
结果如下:

2903





