xml格式标签转换为YOLO标签

xml格式标签转换为YOLO标签

因为只有xml格式的打标签软件,打完后发现yolo要专用的格式,自己转换了下,用了re和os

YOLO标签格式

<object-class> <x> <y> <width> <height>

0 0.412500 0.318981 0.358333 0.636111

XML格式

<?xml version="1.0" ?>
<doc>
	<path>C:\Users\xx\Desktop\ChestHeart\picture\001.jpeg</path>
	<outputs>
		<object>
			<item>
				<name>heart</name>
				<bndbox>
					<xmin>513</xmin>
					<ymin>546</ymin>
					<xmax>1013</xmax>
					<ymax>1066</ymax>
				</bndbox>
			</item>
			<item>
				<name>chest</name>
				<bndbox>
					<xmin>77</xmin>
					<ymin>214</ymin>
					<xmax>1253</xmax>
					<ymax>1270</ymax>
				</bndbox>
			</item>
		</object>
	</outputs>
	<time_labeled>1615556133705</time_labeled>
	<labeled>true</labeled>
	<size>
		<width>1360</width>
		<height>1341</height>
		<depth>3</depth>
	</size>
</doc>

转换代码

import re
import os


def to_one(name_list, xmin, ymin, xmax, ymax, width, height):
    data = []
    num = 1
    for x1, y1, x2, y2 in zip(xmin, ymin, xmax, ymax):
        x1 = float(x1)
        y1 = float(y1)
        x2 = float(x2)
        y2 = float(y2)
        w1 = float(width[0])
        h1 = float(height[0])

        x = (x2 - x1) / 2 + x1
        y = (y2 - y1) / 2 + y1
        w = x2 - x1
        h = y2 - y1
        x = x / w1
        y = y / h1
        w = w / w1
        h = h / h1
        data.append(' '.join([str(num), str(x), str(y), str(w), str(h),'\n']))
        num += 1
    # print(data)
    global i
    with open("%d.txt" % i, 'w') as f:
        f.writelines(data)
        i += 1


def xml_to_yolo(path):
    files_list = os.listdir(path)
    files_path = []
    for file in files_list:
        files_path.append(os.path.join(path, file))
    for file in files_path:
        with open(file, 'r') as f:
            data = f.read()
            name_list = re.findall('<name>(.*?)</name>', data)
            xmin = re.findall('<xmin>(.*?)</xmin>', data)
            ymin = re.findall('<ymin>(.*?)</ymin>', data)
            xmax = re.findall('<xmax>(.*?)</xmax>', data)
            ymax = re.findall('<ymax>(.*?)</ymax>', data)
            width = re.findall('<width>(.*?)</width>', data)
            height = re.findall('<height>(.*?)</height>', data)
            to_one(name_list, xmin, ymin, xmax, ymax, width, height)


def make_dir():
    if os.path.exists('.//lables'):
        os.chdir(".//lables")
    else:
        os.makedirs(".//lables")
        os.chdir(".//lables")


if __name__ == '__main__':
    i = 1
    make_dir()
    xml_to_yolo('F:\python\YOLO\ChestHeart\outputs')
    print('完成')

结果

1 0.5610294117647059 0.6010439970171514 0.36764705882352944 0.3877703206562267 
2 0.4889705882352941 0.5533184190902312 0.8647058823529412 0.7874720357941835 

上一篇:YOLO-FastestV2:更快,更轻!移动端高达300 FPS!参数量仅250k


下一篇:labelme转YOLO格式脚本