labelimg标注的VOC格式标签xml文件和yolo格式标签txt文件相互转换
要实现VOC格式标签xml文件和YOLO格式标签txt文件的互相转换,需要编写相应的转换代码。以下是Python代码示例:
import os
import glob
import xml.etree.ElementTree as ET
import numpy as np
# VOC标签转YOLO标签
def convert_voc_to_yolo(xml_file, txt_file, classes):
with open(txt_file, 'w') as f:
tree = ET.parse(xml_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'):
cls = obj.find('name').text
if cls not in classes:
continue
cls_id = classes.index(cls)
xml_box = obj.find('bndbox')
xmin = int(xml_box.find('xmin').text)
ymin = int(xml_box.find('ymin').text)
xmax = int(xml_box.find('xmax').text)
ymax = int(xml_box.find('ymax').text)
x_center = (xmin + xmax) / 2 / w
y_center = (ymin + ymax) / 2 / h
width = (xmax - xmin) / w
height = (ymax - ymin) / h
f.write(' '.join([str(cls_id), str(x_center), str(y_center), str(width), str(height)]) + '\n')
# YOLO标签转VOC标签
def convert_yolo_to_voc(txt_file, xml_file, classes):
tree = ET.parse(xml_file)
root = tree.getroot()
size = root.find('size')
w = int(size.find('width').text)
h = int(size.find('height').text)
with open(txt_file, 'r') as f:
lines = f.readlines()
for line in lines:
cls_id, x_center, y_center, width, height = [float(x) for x in line.split()]
xmin = int((2 * x_center * w) - (width * w))
ymin = int((2 * y_center * h) - (height * h))
xmax = int(xmin + (width * w))
ymax = int(ymin + (height * h))
obj = ET.Element('object')
name = ET.SubElement(obj, 'name')
name.text = classes[int(cls_id)]
bndbox = ET.SubElement(obj, 'bndbox')
xmin_tag = ET.SubElement(bndbox, 'xmin')
xmin_tag.text = str(xmin)
ymi
评论已关闭