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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值