ElementTree as ET
import os
from os import getcwd
sets = ['train', 'val', 'test']
classes = ["Gun", "Knife","Wrench","Pliers", "Scissors"]
def convert(size, box):dw = 1. / (size[0])dh = 1. / (size[1])x = (box[0] + box[1]) / 2.0 - 1y = (box[2] + box[3]) / 2.0 - 1w = box[1] - box[0]h = box[3] - box[2]x = x * dww = w * dwy = y * dhh = h * dhreturn x, y, w, hdef convert_annotation(image_id):in_file = open('E:/chongda/SIXray/Annotations/%s.xml' % (image_id), encoding='UTF-8')out_file = open('E:/chongda/SIXray/labels/%s.txt' % (image_id), 'w')tree = ET.parse(in_file)root = t()w = int(root.find('size').find('width').text)h = int(root.find('size').find('height').text)for obj in root.iter('object'):try:cls = obj.find('name').textexcept:continueif cls not in classes == 1:continuecls_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))b1, b2, b3, b4 = b# 标注越界修正if b2 > w:b2 = wif b4 > h:b4 = hb = (b1, b2, b3, b4)bb = convert((w, h), b)out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + 'n')#划分训练集,测试集,验证集
def test():import osimport randomimport argparseparser = argparse.ArgumentParser()# xml文件的地址,根据自己的数据进行修改 xml一般存放在Annotations下parser.add_argument('--xml_path', default=r'E:chongdaSIXraylabels', type=str, help='input xml label path')# 数据集的划分,地址选择自己数据下的ImageSets/Mainparser.add_argument('--txt_path', default=r'E:chongdaSIXrayImageSetsMain', type=str, help='output txt label path')opt = parser.parse_args()#训练集:验证集的比例trainval_percent = 0.9#训练集+验证集:测试集的比例train_percent = 0.9xmlfilepath = l_pathtxtsavepath = _pathtotal_xml = os.listdir(xmlfilepath)if not ists(txtsavepath):os.makedirs(txtsavepath)random.seed(2022)num = len(total_xml)list_index = range(num)tv = int(num * trainval_percent)tr = int(tv * train_percent)trainval = random.sample(list_index, tv)train = random.sample(trainval, tr)file_trainval = open(txtsavepath + '/', 'w')file_test = open(txtsavepath + '/', 'w')file_train = open(txtsavepath + '/', 'w')file_val = open(txtsavepath + '/', 'w')for i in list_index:name = total_xml[i][:-4] + 'n'if i in trainval:file_trainval.write(name)if i in train:file_train.write(name)else:file_val.write(name)else:file_test.write(name)file_trainval.close()file_train.close()file_val.close()file_test.close()
#根据划分的数据集生成对应的文件路径
def test2():for image_set in sets:image_ids = open(r'E:chongdaSIXrayImageSetsMain%s.txt' % (image_set)).read().strip().split()list_file = open(r'E:chongdaSIXray%s.txt' % (image_set), 'w')for image_id in image_ids:list_file.write('E:chongdaSIXrayimages%s.jpgn' % (image_id))list_file.close()
#将原数据标签转化成我们需要的标签
def test3():path = r'E:chongdaSIXrayAnnotations'for image_id in os.listdir(path):convert_annotation(image_id[:-4])
本文发布于:2024-02-01 20:11:07,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170678946839151.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |