import os
import cv2
from PIL import Image
import torch
import random
import numpy as np
import math
import matplotlib.pyplot as plt
# 绕pointx,pointy逆时针旋转
def Nrotate(angle,valuex,valuey,pointx,pointy):
'''
srx = (x-pointx)*cos(angle) + (y-pointy)*sin(angle)+pointx
sry = (y-pointy)*cos(angle) - (x-pointx)*sin(angle)+pointy
'''
valuex = np.array(valuex)
valuey = np.array(valuey)
nRotatex = (valuex-pointx)*math.cos(angle) - (valuey-pointy)*math.sin(angle) + pointx
nRotatey = (valuex-pointx)*math.sin(angle) + (valuey-pointy)*math.cos(angle) + pointy
return nRotatex, nRotatey
# 绕pointx,pointy顺时针旋转
def Srotate(angle,valuex,valuey,pointx,pointy):
valuex = np.array(valuex)
valuey = np.array(valuey)
sRotatex = (valuex-pointx)*math.cos(angle) + (valuey-pointy)*math.sin(angle) + pointx
sRotatey = (valuey-pointy)*math.cos(angle) - (valuex-pointx)*math.sin(angle) + pointy
return sRotatex,sRotatey
#旋转框
def rotation(box,angle):
'''
:param box: [x1,y1,x2,y2]
:param angle: for example 45
:return:
'''
centerx = (box[0] + box[2]) / 2 #torch.FloatTensor([2.0]).cuda()
centery = (box[1] + box[3]) / 2
x1, y1 = Srotate(math.radians(angle), box[0], box[1], centerx, centery)
x2, y2 = Srotate(math.radians(angle), box[0], box[3], centerx, centery)
x3, y3 = Srotate(math.radians(angle), box[2], box[1], centerx, centery)
x4, y4 = Srotate(math.radians(angle), box[2], box[3], centerx, centery)
xmin = min(x1, x2, x3, x4)
xmax = max(x1, x2, x3, x4)
ymin = min(y1, y2, y3, y4)
ymax = max(y1, y2, y3, y4)
return [xmin,ymin,xmax,ymax]
if __name__=="__main__":
img_position = '33955cf576299df088aa4b62afbdee6c-00818.jpg'
# image = cv2.imread(img_position, cv2.IMREAD_COLOR)
# img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image=Image.open(img_position)
image = image.rotate(15)
plt.ion()
fig = plt.figure(figsize=(5, 5))
plt.imshow(image)
currentAxis = plt.gca()
roi=[512 ,250, 652,454]
currentAxis.add_patch(plt.Rectangle((roi[0], roi[1]), roi[2]-roi[0],
roi[3]-roi[1], fill=False,
edgecolor='red', linewidth=1.5))
# for epoch in range(10):
# angel=random.randint(1,90)
roi = rotation(box=[512 ,250, 652,454],angle=15)
currentAxis.add_patch(plt.Rectangle((roi[0], roi[1]), roi[2]-roi[0],
roi[3]-roi[1], fill=False,
edgecolor='orange', linewidth=1.5))
# name = img_position.split('/')[-1]
# target_dir ='./label_imgs/'
# if not os.path.exists(target_dir):
# os.makedirs(target_dir)
# plt.savefig(target_dir + name, format='jpg', transparent=True, dpi=300, pad_inches=0)
plt.show()
plt.pause(20)
plt.close()
原图:
旋转图和框(取了最大外接矩阵用于抠图):