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()
txt转xml
最新推荐文章于 2024-04-17 08:54:01 发布