import xml.etree.ElementTree as ET
from os import getcwd
import glob
import shutil
import os
# drone person car
# classes = ["", "person", "vehicle"]
# classes = ["liner", "bulk carrier", "warship", "sailboat", "canoe", "container ship", "fishing boat"]
classes = []
dataset_dir = "E:/数据集/艾睿光电红外数据集/双光车载/infrad_person_car/train/images/"
xml_dir = "E:/数据集/艾睿光电红外数据集/双光车载/infrad_person_car/train/labels_xml/"
dataset_save_dir = "E:/数据集/艾睿光电红外数据集/双光车载/infrad_person_car/train/labels_yolo/"
cls_map = {}
# for cls in classes:
# cls_map[cls] = 0
if not os.path.exists(dataset_save_dir):
os.makedirs(dataset_save_dir)
def convert(size, box):
dw = 1.0 / size[0]
dh = 1.0 / size[1]
x = (box[0] + box[1]) / 2.0
y = (box[2] + box[3]) / 2.0
w = box[1] - box[0]
h = box[3] - box[2]
x = x * dw
w = w * dw
y = y * dh
h = h * dh
return (x, y, w, h)
def convert_annotation(image_name):
# in_file = open('./indata/' + image_name[:-3] + 'xml') # xml文件路径
f = open(xml_dir + image_name[:-3] + 'xml', 'r', encoding='utf-8')
xml_text = f.read()
root = ET.fromstring(xml_text)
f.close()
size = root.find('size')
w = int(size.find('width').text)
h = int(size.find('height').text)
contains = False
for obj in root.iter('object'):
cls = obj.find('name').text
if cls not in classes:
classes.append(cls)
cls_map[cls] = 0
# print(cls)
# continue
cls_map[cls] = cls_map[cls] + 1
if w == 0 or h == 0:
continue
contains = True
out_file = open(dataset_save_dir + '/' + image_name[:-4] + '.txt', 'a') # 转换后的txt文件存放路径
print(out_file)
cls_id = classes.index(cls)
xmlbox = obj.find('bndbox')
b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
float(xmlbox.find('ymax').text))
bb = convert((w, h), b)
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
out_file.close()
# if contains:
# shutil.copy('E:/数据集/艾睿光电红外数据集/红外航拍数据集/dataset/' + image_name, 'E:/数据集/zzbs-hw(人车)/infiray_images/' + image_name[:-4] + "-infiray.jpg")
# print(image_name, "not contains any obj....")
if __name__ == '__main__':
for image_path in glob.glob(dataset_dir + '*.jpg'): # 每一张图片都对应一个xml文件这里写xml对应的图片的路径
print(image_path)
image_name = image_path.split('\\')[-1]
convert_annotation(image_name)
# input()
print(cls_map)