yolo格式转xml格式

import os
from PIL import Image
import glob

yolo_img = 'VOC/JPEGImages/'
yolo_txt = 'VOC/YOLO/'
voc_xml = 'VOC/Annotations/'

# 目标类别
labels = ["lighthouse",  "sailboat",  "buoy", "railbar", "cargoship", "navalvessels", "passengership", "dock", "submarine", "fishingboat"]
# 匹配文件路径下的所有jpg文件,并返回列表
img_glob = glob.glob(yolo_img + '*.jpg')

img_base_names = []

for img in img_glob:
    # os.path.basename:取文件的后缀名
    img_base_names.append(os.path.basename(img))

img_pre_name = []

for img in img_base_names:
    # os.path.splitext:将文件按照后缀切分为两块
    temp1, temp2 = os.path.splitext(img)
    img_pre_name.append(temp1)
    print(f'imgpre:{img_pre_name}')
for img in img_pre_name:
    with open(voc_xml + img + '.xml', 'w') as xml_files:
        image = Image.open(yolo_img + img + '.jpg')
        img_w, img_h = image.size
        xml_files.write('\n')
        xml_files.write('   folder\n')
        xml_files.write(f'   {img}.jpg\n')
        xml_files.write('   \n')
        xml_files.write('   Unknown\n')
        xml_files.write('   \n')
        xml_files.write('   \n')
        xml_files.write(f'     {img_w}\n')
        xml_files.write(f'     {img_h}\n')
        xml_files.write(f'     3\n')
        xml_files.write('   \n')
        xml_files.write('   0\n')
        with open(yolo_txt + img + '.txt', 'r') as f:
            # 以列表形式返回每一行
            lines = f.read().splitlines()
            for each_line in lines:
                line = each_line.split(' ')
                xml_files.write('   \n')
                xml_files.write(f'      {labels[int(line[0])]}\n')
                xml_files.write('      Unspecified\n')
                xml_files.write('      0\n')
                xml_files.write('      0\n')
                xml_files.write('      \n')
                center_x = round(float(line[1]) * img_w)
                center_y = round(float(line[2]) * img_h)
                bbox_w = round(float(line[3]) * img_w)
                bbox_h = round(float(line[4]) * img_h)
                xmin = str(int(center_x - bbox_w / 2))
                ymin = str(int(center_y - bbox_h / 2))
                xmax = str(int(center_x + bbox_w / 2))
                ymax = str(int(center_y + bbox_h / 2))
                xml_files.write(f'         {xmin}\n')
                xml_files.write(f'         {ymin}\n')
                xml_files.write(f'         {xmax}\n')
                xml_files.write(f'         {ymax}\n')
                xml_files.write('      \n')
                xml_files.write('   \n')
        xml_files.write('')

你可能感兴趣的:(python)