将xml标簽轉換為txt(voc格式轉換為yolo友善進行訓練)
文章目錄
- 将xml标簽轉換為txt(voc格式轉換為yolo友善進行訓練)
-
- 一、前言
- 二、程式
- 三、跑通示範
-
- 1、修改classes為你的資料集的classes
- 2、運作:輸入圖像與标注檔案夾絕對位址
- 四、結果如下:
一、前言
檢索一下其他人的之後,感覺沒有我的好用,将自己的代碼貢獻一下
二、程式
import xml.etree.ElementTree as ET
import os
from os import listdir, getcwd
classes = ["bed", "water horse bucket"] # 換上你标簽
def convert(size, box):
dw = 1.0 / size[0]
dh = 1.0 / size[1]
x = (box[0] + box[1]) / 2.0
y = (box[2] + box[3]) / 2.0
w = box[1] - box[0]
h = box[3] - box[2]
x = x * dw
w = w * dw
y = y * dh
h = h * dh
return (x, y, w, h)
def convert_annotation(image_name,labelPath):
# in_file = open(os.path.join(labelPath,image_name[:-3] + 'xml')) # xml檔案路徑
out_file = open(os.path.join(labelPath+'TXT',image_name[:-3] + 'txt'), 'w') # 轉換後的txt檔案存放路徑
in_file = open(os.path.join(labelPath,image_name[:-3] + 'xml')) # xml檔案路徑
xml_text = in_file.read()
root = ET.fromstring(xml_text)
in_file.close()
size = root.find('size')
w = int(size.find('width').text)
h = int(size.find('height').text)
# print(root.iter('object'))
for obj in root.iter('object'):
cls = obj.find('name').text
if cls not in classes:
print(cls)
continue
cls_id = classes.index(cls)
xmlbox = obj.find('bndbox')
b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
float(xmlbox.find('ymax').text))
bb = convert((w, h), b)
#print(bb)
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
wd = getcwd()
if __name__ == '__main__':
imgNmae=input('輸入圖像檔案夾的絕對位址:')
labelPath=input('輸入xml标注的檔案夾的絕對位址:')
#imgNmae='E:\資料集\建立檔案夾//bed//bed\data\img'
#labelPath='E:\資料集\建立檔案夾//bed/bed\data\labels'
if not os.path.isdir(labelPath+'TXT'):
os.mkdir(labelPath+'TXT')
for image_path in os.listdir(imgNmae): # 每一張圖檔都對應一個xml檔案這裡寫xml對應的圖檔的路徑
#image_name = image_path.split('\\')[-1]
print(image_path)
convert_annotation(image_path,labelPath)
三、跑通示範
1、修改classes為你的資料集的classes
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLxQWZkFTOyQTOyEzYlBzY5EGOkRjNkRGNzMTN1YjNlF2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)