labelImg工具 xml格式 修改成 txt格式保存

import os
import xml.etree.ElementTree as ET

dirpath = r'W:\images'  # 原來存放xml文件的目錄
newdir = r'W:\labels'  # 修改label後形成的txt目錄

if not os.path.exists(newdir):
    os.makedirs(newdir)

dict_info = {'smoke': 0}  # 有幾個 屬性 填寫幾個

for fp in os.listdir(dirpath):
    if fp.endswith('.xml'):
        root = ET.parse(os.path.join(dirpath, fp)).getroot()

        xmin, ymin, xmax, ymax = 0, 0, 0, 0
        sz = root.find('size')
        width = float(sz[0].text)
        height = float(sz[1].text)
        filename = root.find('filename').text
        for child in root.findall('object'):  # 找到圖片中的所有框

            sub = child.find('bndbox')  # 找到框的標註值並進行讀取
            label = child.find('name').text
            label_ = dict_info.get(label)
            if label_:
                label_ = label_
            else:
                label_ = 0
            xmin = float(sub[0].text)
            ymin = float(sub[1].text)
            xmax = float(sub[2].text)
            ymax = float(sub[3].text)
            try:  # 轉換成yolov3的標籤格式,需要歸一化到(0-1)的範圍內
                x_center = (xmin + xmax) / (2 * width)
                x_center = '%.6f' % x_center
                y_center = (ymin + ymax) / (2 * height)
                y_center = '%.6f' % y_center
                w = (xmax - xmin) / width
                w = '%.6f' % w
                h = (ymax - ymin) / height
                h = '%.6f' % h
            except ZeroDivisionError:
                print(filename, '的 width有問題')
            with open(os.path.join(newdir, fp.split('.xml')[0] + '.txt'), 'a+') as f:
                f.write(' '.join([str(label_), str(x_center), str(y_center), str(w), str(h) + '\n']))
print('ok')

代碼很簡單,只是簡單記錄一下

發佈了54 篇原創文章 · 獲贊 96 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章