xml转txt脚本

import xml.etree.ElementTree as ET
import os

classes = ["钓鱼"]

def convert(size, box):
    dw = 1. / (size[0])
    dh = 1. / (size[1])
    x_max = box[0] + box[2]
    y_max = box[1] + box[3]
    x = (box[0] + x_max) / 2.0
    y = (box[1] + y_max) / 2.0
    x = x * dw
    w = box[2] * dw
    y = y * dh
    h = box[3] * dh
    return x, y, w, h  ##最后返回的坐标是中心点坐标的比例,宽高的比例。


def convert_annotation(image_id, in_file, out_file):
    txt_file = open(out_file + '/%s.txt' % (image_id), 'w')

    try:
        xml_file = open(in_file + '/%s.xml' % (image_id), encoding='UTF-8')
        tree = ET.parse(xml_file)
    except:
        return
    root = tree.getroot()
    size = root.find('size')
    w = float(size.find('width').text)
    h = float(size.find('height').text)
    try:
        for obj in root.iter('object'):
            cls = obj.find('name').text
            if cls in classes:
                cls_id = classes.index(cls)
                xmlbox = obj.find('bndbox')
                b = (float(xmlbox.find('xmin').text), float(xmlbox.find('ymin').text), float(xmlbox.find('xmax').text),
                     float(xmlbox.find('ymax').text))
                b1, b2, b3, b4 = b
                # 标注越界修正
                if b3 > w:
                    b2 = w
                if b4 > h:
                    b4 = h
                b = (b1, b2, b3-b1, b4-b2)   ##把x,y,w,h转化成yolo标签格式
                bb = convert((w, h), b)
                txt_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
            else:
                print("label not in classes")
                print(cls)
    except:
        print("no obj")
    return

imageDir = 'data/images'
xml_file = 'data/xml'
out_file = 'data/txt'

img_ids = os.listdir(imageDir)
for img_id in img_ids:
    image_id = img_id.strip('.jpg')
    convert_annotation(image_id, xml_file, out_file)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值