'''
2020/6/15,标注文件转换xml转txt(vol to yolo)转完后需添加labels文件,即数字序号对应的标签名。
'''
import xml.etree.ElementTree as ET
import numpy as np
import pickle
import os
import cv2
from os import listdir, getcwd
from os.path import join
classes = ['Boeing737', 'Boeing747', 'Boeing777', 'Boeing787', 'C919', 'A220', 'A321', 'A330', 'A350', 'ARJ21',
'other-airplane', 'Passenger Ship', 'Motorboat', 'Fishing Boat', 'Tugboat', 'Engineering Ship',
'Liquid Cargo Ship', 'Dry Cargo Ship', 'Warship', 'other-ship', 'Small Car', 'Bus', 'Cargo Truck',
'Dump Truck', 'Van', 'Trailer', 'Tractor', 'Excavator', 'Truck Tractor', 'other-vehicle', 'Basketball Court',
'Tennis Court', 'Football Field', 'Baseball Field', 'Intersection', 'Roundabout', 'Bridge']
def convert(size, box):
dw = 1. / (size[0])
dh = 1. / (size[1])
x = (box[0] + box[1]) / 2.0 - 1
y = (box[2] + box[3]) / 2.0 - 1
w = box[1] - box[0]
h = box[3] - box[2]
x = x * dw
w = w * dw
y = y * dh
h = h * dh
if w >= 1:
w = 0.99
if h >= 1:
h = 0.99
return (x, y, w, h)
def convert_annotation(rootpath, xmlpath, xmlname):
xmlfile = os.path.join(xmlpath, xmlname)
with open(xmlfile, "r", encoding='UTF-8') as in_file:
txtname = xmlname[:-4] + '.txt'
txtpath = rootpath + '/labelTxt' # 生成的.txt文件会被保存在labelTxt目录下
if not os.path.exists(txtpath):
os.makedirs(txtpath)
txtfile = os.path.join(txtpath, txtname)
with open(txtfile, "w+", encoding='UTF-8') as out_file:
tree = ET.parse(in_file)
root = tree.getroot()
size = root.find('size')
w = int(size.find('width').text) # 图片的宽
h = int(size.find('height').text)
# print(w, h)
out_file.truncate()
for obj in root.iter('object'):
possibleresult = obj.find('possibleresult')
cls_name = possibleresult.find('name').text
if cls_name not in classes:
print("Appear not clear class name!!!!")
exit()
cls_name = cls_name.replace(" ", "-")
points = obj.find('points')
data = ""
for i in range(0, len(points) - 1): # 只遍历前四个点
point = points[i]
xy = point.text.split(",")
x = int(float(xy[0]))
y = int(float(xy[1]))
data = data + str(x) + " "
data = data + str(y) + " "
data = data + cls_name + " " + str(0)
print(data)
out_file.write(data + '\n')
if __name__ == "__main__":
rootpath = 'train'
xmlpath = rootpath + '/labelXml' # 标签文件所在的路径
list = os.listdir(xmlpath)
for i in range(0, len(list)):
path = os.path.join(xmlpath, list[i])
if ('.xml' in path) or ('.XML' in path):
convert_annotation(rootpath, xmlpath, list[i])
print('---------------done--------------', i, '----------------------------------------')
else:
print('not xml file', i)
xml to DOTA
最新推荐文章于 2024-04-13 00:00:00 发布