CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hukaixuan19970627

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: hukaixuan19970627/yolov5_obb
Path: blob/master/tools/Xml2Txt.py
Views: 475
1
import xml.etree.ElementTree as ET
2
from DOTA_devkit import dota_utils as util
3
import os
4
import shutil
5
6
def DroneVehicle2DOTA(xmlpath, txtpath, extractclassname, specified_class):
7
"""
8
Trans DroneVehicle xml farmat to DOTA labels format
9
Args:
10
xmlpath: the path of xml with DroneVehicle2DOTA format
11
txtpath: the path of txt with DOTA format
12
extractclassname: the category
13
specified_class: only output single category
14
"""
15
if os.path.exists(txtpath):
16
shutil.rmtree(txtpath) # delete output folder
17
os.makedirs(txtpath) # make new output folder
18
filelist = util.GetFileFromThisRootDir(xmlpath) # fileist=['/.../0001.xml', ...]
19
for xmlfile in filelist: # fullname='/.../0001.xml'
20
name = os.path.splitext(os.path.basename(xmlfile))[0] # name='0001'
21
out_file = open(os.path.join(txtpath, name + '.txt'), 'w')
22
tree = ET.parse(xmlfile)
23
root = tree.getroot()
24
for obj in root.iter('object'):
25
cls = obj.find('name')
26
if cls == None:
27
continue
28
cls = cls.text
29
diffcult = obj.find('difficult')
30
diffcult = int(diffcult.text) if diffcult != None else 0
31
32
if diffcult < 2:
33
# cls = cls.replace(' ', '_')
34
cls = specified_class
35
polygon = obj.find('polygon')
36
if polygon == None:
37
continue
38
polygon = [int(polygon.find(x).text) for x in ('x1', 'y1', 'x2', 'y2', 'x3', 'y3', 'x4', 'y4')]
39
out_file.write(" ".join([str(a) for a in (*polygon, cls, diffcult)]) + '\n')
40
else:
41
print(f'{cls} is not in the extractclassname or diffcult is {diffcult}')
42
43
if __name__ == "__main__":
44
xmlpath = ['/media/test/DroneVehicle/val/raw/vallabel',
45
'/media/test/DroneVehicle/val/rays/vallabelr',
46
'/media/test/DroneVehicle/train/raw/trainlabel',
47
'/media/test/DroneVehicle/train/rays/trainlabelr']
48
49
txtpath = ['/media/test/DroneVehicle/val/raw/vallabel_txt',
50
'/media/test/DroneVehicle/val/rays/vallabelr_txt',
51
'/media/test/DroneVehicle/train/raw/trainlabel_txt',
52
'/media/test/DroneVehicle/train/rays/trainlabelr_txt']
53
extractclassname = {'car', 'truck', 'feright_car', 'feright car', 'bus', 'van'}
54
specified_class = 'vehicle'
55
for (xml, txt) in zip(xmlpath, txtpath):
56
print(f"{xml} is converting to {txt}")
57
DroneVehicle2DOTA(xml, txt, extractclassname, specified_class)
58