前言
对yolo做数据增强,旋转图片后,标签的坐标也要跟着旋转,网上看了一大堆不是旋转的图片有问题就是旋转后的标签有问题,自己写了一个,欢迎指点评论。
直接上代码,有注释,看不懂的欢迎评论区和私信
import cv2
import numpy as np
import os
from math import cos,sin
jiaodu=30
zq_id="zq1"
img_folder="images"
img_save_folder="images"
txt_folder="labelTxt"
txt_save_folder="labelTxt"
Add_label_information=False
def rotate_xy(x, y, angle, cx, cy):
"""
点(x,y) 绕(cx,cy)点旋转
"""
angle = angle * np.pi / 180
x_new = (x - cx) * cos(angle) - (y - cy) * sin(angle) + cx
y_new = (x - cx) * sin(angle) + (y - cy) * cos(angle) + cy
return [x_new, y_new]
for img_path in os.listdir(img_folder):
img=cv2.imread(img_folder+"/"+img_path)
height,width=img.shape[:2]
cx,cy=height/2,width/2
M=cv2.getRotationMatrix2D((cx,cy),jiaodu,1)
dst=cv2.warpAffine(img,M,(height,width),borderValue=(255,255,255))
cv2.imwrite(img_save_folder+"/"+os.path.splitext(img_path)[0]+zq_id+'.jpg',dst)
txt=open(txt_folder+"/"+os.path.splitext(img_path)[0]+".txt").read()
points_list=[]
for i in range(8)[::2]:
points_list.append([txt.split(' ')[i],txt.split(' ')[i+1]])
new_newpoints=[]
for i in points_list:
new_newpoints.append(rotate_xy(float(i[0]),float(i[1]),-jiaodu,cx,cy))
if Add_label_information:
sava_txt=''
for i in new_newpoints:
for j in i:
sava_txt+=str(j)+' '
sava_txt+=txt.split(' ')[-2]+' '+txt.split(' ')[-1]
dir_name=txt_save_folder+"/"+os.path.splitext(img_path)[0]+zq_id+".txt"
else:
sava_txt=''
for i in new_newpoints:
for j in i:
sava_txt+=str(j)+' '
dir_name=txt_save_folder+"/"+os.path.splitext(img_path)[0]+zq_id+".txt"
fb = open(dir_name ,mode='w',encoding='utf-8')
fb.write(str(sava_txt))
放一下我的目录结构
images和labelTxt分别存放需要增强的图片和标签 这里我增强后的路径也写的这两个,增强后的图片和标签也保存在这两个文件夹里面 我的label文件是这样的,前面八个是四个点的坐标都一样 最后面我是两个标签,如果只有一个标签在代码里面改一下加入标签信息那里,注释有写
总结
人懒此处省略,有问题欢迎评论区,阿巴阿巴。。。。。。。。。。。。。
|