import xml.etree.ElementTree as ET
import os
import shutil
import random
def convert_annotation(cls, cls_id, image_id):
in_root = root_path + '/%s.xml' %(image_id)
out_root = root_path + './../convert/%s/%s.txt' % (cls, image_id)
in_file = open(in_root)
out_file = open(out_root, 'w')
tree = ET.parse(in_file)
root = tree.getroot()
size = root.find('size')
size_width = int(size.find('width').text)
size_height = int(size.find('height').text)
for obj in root.iter('object'):
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)]
if b[1] > size_width:
b[1] = size_width
if b[3] > size_height:
b[3] = size_height
txt_data=[((b[0]+b[1])/2.0-1)/size_width,((b[2]+b[3])/2.0-1)/size_height,(b[1]-b[0])/size_width,(b[3]-b[2])/size_height]
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in txt_data]) + '\n')
path = './'
classes=['chairs', 'keyboards', 'mouses', 'people', 'phones']#标签名
for num, cls in enumerate(classes):
root_path = os.path.abspath(path + cls)
img_path = os.path.join(root_path, '')
imglist = [file for file in os.listdir(img_path) if file.endswith('.xml')]
print(imglist)
for img_id in imglist:
img_id=img_id[:-4]
convert_annotation(cls, num, img_id)
数据标注:将xml 格式转换txt 并且没有标注class类文件
于 2022-03-14 18:32:55 首次发布