txt转xml

该博客介绍了如何使用Python将jpg图片及其对应的txt标注文件转换为VOC2007格式的XML文件,包括读取图片尺寸、解析txt标签,并将坐标信息写入XML中。
import os, math
import glob
from PIL import Image
#img_999.jpg gt_img_1.txt
src_img_dir = "./jpg/" # 图片地址
src_txt_dir = "./txt/" # txt文件地址
save_xml_dir = './xml/' # 转后的xml保存地址

img_Lists = glob.glob(src_img_dir + '*.jpg')

img_basenames = [] # e.g. 100.jpg
for item in img_Lists:
    img_basenames.append(os.path.basename(item))

img_names = [] # e.g. 100
for item in img_basenames:
    temp1, temp2 = os.path.splitext(item)
    img_names.append(temp1)

for img in img_names:
    im = Image.open((src_img_dir + img + '.jpg'))
    width, height = im.size

    # open the crospronding txt file
    gt = open(src_txt_dir + img + '.txt').read().splitlines()

    # write in xml file
    f = open(save_xml_dir + img + '.xml','w',encoding='utf8')
    # xml_file = open((src_txt_dir + img + '.xml'), 'w')
    f.writelines('<annotation>\n')
    f.writelines('    <folder>VOC2007</folder>\n')
    f.writelines('    <filename>' + str(img) + '.jpg' + '</filename>\n')
    f.writelines('    <size>\n')
    f.writelines('        <width>' + str(width) + '</width>\n')
    f.writelines('        <height>' + str(height) + '</height>\n')
    f.writelines('        <depth>3</depth>\n')
    f.writelines('    </size>\n')

    # write the region of text on xml file
    for img_each_label in gt:
        _,centerx,centery,w,h,class_name = img_each_label.split(' ')
        class_name = "matter"
        newcenterx = float(centerx) * width
        newcentery = float(centery) * height
        neww = float(w) * width
        newh = float(h) * height
        x1 = math.ceil(newcenterx - neww/2)
        y1 = math.ceil(newcentery - newh/2)
        x2 = math.ceil(newcenterx + neww/2)
        y2 = math.ceil(newcentery + newh/2)
        f.writelines('    <object>\n')
        f.writelines('        <name>' + class_name + '</name>\n')
        f.writelines('        <pose>Unspecified</pose>\n')
        f.writelines('        <truncated>0</truncated>\n')
        f.writelines('        <difficult>0</difficult>\n')
        f.writelines('        <bndbox>\n')
        f.writelines('            <xmin>' + str(x1) + '</xmin>\n')
        f.writelines('            <ymin>' + str(y1) + '</ymin>\n')
        f.writelines('            <xmax>' + str(x2) + '</xmax>\n')
        f.writelines('            <ymax>' + str(y2) + '</ymax>\n')
        f.writelines('        </bndbox>\n')
        f.writelines('    </object>\n')

    f.writelines('</annotation>')

    f.flush()

    f.close()
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值