当前位置:网站首页>VOC format label to YOLO format

VOC format label to YOLO format

2022-08-09 07:32:00 qq_52217283

VOC to Yolo format code:​​​​​​​​

import osimport xml.etree.ElementTree as ET# Convert x1, y1, x2, y2 to the x, y, w, h format required by yolodef voc_to_yolo_wh(size, box):dw = 1. / size[0]dh = 1. / size[1]x = (box[0] + box[2]) / 2 * dwy = (box[1] + box[3]) / 2 * dhw = (box[2] - box[0]) * dwh = (box[3] - box[1]) * dhreturn x, y, w, h # return the normalized values# Get the classes category in all xml, return (list/array)def get_cls_list(xml_path):result_list = []for file in os.listdir(xml_path):tree = ET.parse(xml_path + file)root = tree.getroot()for obj in root.iter('object'):cls = obj.find('name').textif cls not in result_list:result_list.append(cls)return result_listdef voc_to_yolo(xml_path, save_path, classes):# can print to see if the path is correctif not os.path.exists(xml_path):print("XML path does not exist")return []if len(os.listdir(xml_path)) == 0:print("XML file directory is empty")return []if not os.path.exists(save_path):os.makedirs(save_path)if not classes:classes = get_cls_list(xml_path)# loop through each xml filefor file in os.listdir(xml_path):label_file = xml_path + filesave_file = save_path + file.replace('xml', 'txt')out_file = open(save_file, 'w')# print(label_file)# Start parsing the xml filetree = ET.parse(label_file)root = tree.getroot()size = root.find('size') # The shape value of the imagew = int(size.find('width').text)h = int(size.find('height').text)for obj in root.iter('object'):difficult = obj.find('difficult').textcls = obj.find('name').textif cls not in classes or int(difficult) == 1:continue# Convert name to id subscriptcls_id = classes.index(cls)# Get the entire bounding boxbnd_box = obj.find('bndbox')# xml gives x1, y1, x2, y2box = [float(bnd_box.find('xmin').text), float(bnd_box.find('ymin').text), float(bnd_box.find('xmax').text),float(bnd_box.find('ymax').text)]# Convert x1, y1, x2, y2 to x_center, y_center, w, h format required by yolobbox = voc_to_yolo_wh((w, h), box)# print(save_file)# Write to the target file, the format is id x y w hout_file.write(str(cls_id) + " " + " ".join(str(x) for x in bbox) + '\n')return classesif __name__ == '__main__':# here to change to your own data set pathxml_path_ = 'Annotations/xml/'# This is to be changed to the data set path saved after conversionsave_path_ = 'Annotations/labels/'# Data set label, if it is empty, it will automatically get the label, just get the label in the function return result.Class_Name = []result_classes = voc_to_yolo(xml_path_, save_path_, Class_Name)print("Dataset label:", result_classes)

原网站

版权声明
本文为[qq_52217283]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208090729485816.html