voc-yolo数据集转换
该脚本可以很快帮助大家进行数据集格式转换
- 修改点1见注释@@@@@@@,修改自己数据集的类别
- 修改文件路径in_file = open(‘VOCdevkit/VOC2007/Annotations/%s.xml’,也可以使用绝对路径
import os
import xml.etree.ElementTree as ET
classes = ['228']
def convert(size, box):
dw = 1. / (size[0])
dh = 1. / (size[1])
x = (box[0] + box[1]) / 2.0 - 1
y = (box[2] + box[3]) / 2.0 - 1
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 makedirs(path):
if not os.path.exists(path):
os.makedirs(path)
def convert_annotation(image_id, out_file):
in_file = open('VOCdevkit/VOC2007/Annotations/%s.xml' % (image_id), encoding='utf-8')
tree = ET.parse(in_file)
root = tree.getroot()
size = root.find('size')
w = int(size.find('width').text)
h = int(size.find('height').text)
for obj in root.iter('object'):
difficult = obj.find('difficult').text
cls = obj.find('name').text
if cls not in classes or int(difficult) == 1:
continue
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)[0:8] for a in bb]) + '\n')
def generate_txt(txt_name):
def work(txt_name):
f = open(os.path.join("VOCdevkit/VOC2007/ImageSets/Main", txt_name), encoding='utf-8')
for file_name in f.readlines():
image_id = file_name.split('\n')[0]
out_file = open('VOCdevkit/VOC2007/yolo_labels/%s/%s.txt' % (txt_name.split('.')[0], image_id),
'w', encoding='utf-8')
convert_annotation(image_id, out_file)
if txt_name == "test.txt":
work(txt_name)
elif txt_name == "train.txt":
work(txt_name)
elif txt_name == "trainval.txt":
work(txt_name)
elif txt_name == "val.txt":
work(txt_name)
if __name__ == '__main__':
makedirs('VOCdevkit/VOC2007/yolo_labels/test')
makedirs('VOCdevkit/VOC2007/yolo_labels/train')
makedirs('VOCdevkit/VOC2007/yolo_labels/trainval')
makedirs('VOCdevkit/VOC2007/yolo_labels/val')
txt_paths = os.listdir("VOCdevkit/VOC2007/ImageSets/Main")
for txt_name in txt_paths:
generate_txt(txt_name)