生活随笔
收集整理的這篇文章主要介紹了
VOC2007xml转YOLO的txt格式代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用方法(二選一即可):
- python 這個文件名.py --xml_dir xml文件路徑 --image_dir 圖片所在路徑 --out_dir 輸出文件夾
- 放在和VOC2007同級路徑下運行即可
import os
import xml.etree.ElementTree as ET
import cv2
import argparse
from tqdm import tqdmdef xml_to_txt(xml_dir,img_dir,out_dir):if not os.path.exists(out_dir): # 如果輸出路徑不存在,創建輸出路徑os.makedirs(out_dir)annotations = os.listdir(xml_dir) # 獲取指定文件夾的文件列表#tqdm是用來顯示進度條的,可以改成你原來那樣子就不會有進度條了for i, file in tqdm(enumerate(annotations),desc='已經處理了',total=len(annotations),unit='xml_file'):txt_name = file.split('.')[0] + '.txt'#txt的文件名txt_pos = out_dir + '/' + txt_name#txt文件帶路徑的文件名with open(txt_pos,mode='w') as f_txt:#f_txt是用于txt文件讀寫的文件對象with open(xml_dir+'/'+file,encoding='utf-8') as f_xml:#f_xml是用于xml文件讀寫的文件對象tree = ET.parse(f_xml)root = tree.getroot()for obj in root.iter('object'):src = cv2.imread(img_dir+'/img{:0>5d}.jpg'.format(i+1))width=src.shape[1]height=src.shape[0]xmlbox=obj.find('bndbox')#獲取對應的bndbox中的對應的坐標值文本并轉為int型x_max=int(xmlbox.find('xmax').text)x_min=int(xmlbox.find('xmin').text)y_max=int(xmlbox.find('ymax').text)y_min=int(xmlbox.find('ymin').text)#計算對應的x y w hx = ((x_min + x_max) / 2.0)*(1.0/width)y = ((y_min + y_max) / 2.0)*(1.0/height)w = (x_max-x_min)*(1.0/width)h = (y_max-y_min)*(1.0/height)f_txt.write('0' + ' ')f_txt.write(str(x) + ' ' + str(y) + ' ' + str(w) + ' ' + str(h) + ' ')f_txt.write('\n')if __name__ == '__main__':parser = argparse.ArgumentParser()parser.add_argument('--xml_dir', type=str, default='./VOC2007/Annotations', help='xml文件所在目錄')parser.add_argument('--img_dir', type=str, default='./VOC2007/JPEGImages', help='圖片文件所在目錄')parser.add_argument('--out_dir', type=str, default='./resultLabels', help='輸出文件夾')opt = parser.parse_args()xml_to_txt(opt.xml_dir,opt.img_dir,opt.out_dir)
?
總結
以上是生活随笔為你收集整理的VOC2007xml转YOLO的txt格式代码的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。