使用python语言将xml文件转成yolo中的txt文件

xml文件转成yolo中的txt文件

# coding=utf-8

import os
import xml.dom.minidom
import cv2 as cv


def xml_to_txt(indir, outdir):
    os.chdir(indir)
    xmls = os.listdir('.')
    for i, file in enumerate(xmls):
        file_save = file.split('.')[0] + '.txt'
        file_txt = os.path.join(outdir, file_save)
        f_w = open(file_txt, 'w')
        # actual parsing
        DOMTree = xml.dom.minidom.parse(file)
        annotation = DOMTree.documentElement
        filename = annotation.getElementsByTagName("path")[0]
        imgname = filename.childNodes[0].data
        img_temp = imgname.split('\\')[-1]
        img_temp = os.path.join(image_dir, img_temp)
        image = cv.imread(imgname)
#        cv.imwrite(img_temp, image)
        objects = annotation.getElementsByTagName("object")
        print(file)
        for object in objects:
            bbox = object.getElementsByTagName("robndbox")[0]
            cx = bbox.getElementsByTagName("cx")[0]
            x = float(cx.childNodes[0].data)
            print(x)
            cy = bbox.getElementsByTagName("cy")[0]
            y = float(cy.childNodes[0].data)
            print(y)
            cw = bbox.getElementsByTagName("w")[0]
            w = float(cw.childNodes[0].data)
            print(w)
            ch = bbox.getElementsByTagName("h")[0]
            h = float(ch.childNodes[0].data)
            print(h)
            cangel = bbox.getElementsByTagName("angle")[0]
            angle = float(cangel.childNodes[0].data)
            print(angle)
            cname = object.getElementsByTagName("name")[0]
            name = cname.childNodes[0].data
            print(name)
            x1 = x - w / 2.
            y1 = y - h / 2.
            x2 = x + w / 2.
            y2 = y - h / 2.
            x3 = x + w / 2.
            y3 = y + h / 2.
            x4 = x - w / 2.
            y4 = y + h / 2.
            temp = str(x1) + ' ' + str(y1) + ' ' + str(x2) + ' ' + str(y2) + ' ' + str(x3) + ' ' + str(y3) + ' ' + str(
                x4) + ' ' + str(y4) + ' ' + name + '\n'
            f_w.write(temp)
        f_w.close()


image_dir = 'D:/img'   #img目录
indir = 'D:/xml'  # xml目录
outdir = 'D:/vtal'  # txt目录
xml_to_txt(indir, outdir)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

枭玉龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值