目錄
1. 導入必要的模塊
2. 定義類別名稱
3. 設置文件路徑
完整代碼
1. 導入必要的模塊
import os
import xml.etree.ElementTree as ET
os:用于文件和目錄操作,例如創建目錄、遍歷文件等。
xml.etree.ElementTree:用于解析XML文件,從中提取信息。
2. 定義類別名稱
class_names = ['nest', 'balloon', 'kite', 'trash']
這是一個列表,定義了數據集中所有物體的類別名稱。類別名稱的順序非常重要,因為它們的索引(從0開始)將作為YOLO格式中的class_id。
3. 設置文件路徑
xmlpath = 'C:/Users/10431/Desktop/4517+VOC/Annotations/Annotations/'
txtpath = 'C:/Users/10431/Desktop/4517+VOC/Annotations/yolo/'
xmlpath:VOC格式的XML文件所在的目錄路徑。
txtpath:轉換后的YOLO格式TXT文件將保存的目錄路徑。
完整代碼
import os
import xml.etree.ElementTree as ET# 定義類別名稱
class_names = ['nest', 'balloon', 'kite', 'trash']# 設置輸入和輸出路徑
xmlpath = 'C:/Users/10431/Desktop/4517+VOC/Annotations/Annotations/'
txtpath = 'C:/Users/10431/Desktop/4517+VOC/Annotations/yolo/'# 如果輸出目錄不存在,則創建
if not os.path.exists(txtpath):os.makedirs(txtpath)# 收集所有 XML 文件
files = [os.path.join(root, file) for root, _, files in os.walk(xmlpath) for file in files if file.endswith('.xml')]
number = len(files)
print(f"找到 {number} 個 XML 文件")# 遍歷并轉換每個 XML 文件
for i, xml_file_path in enumerate(files):# 提取文件名并構建輸出路徑name = os.path.splitext(os.path.basename(xml_file_path))[0]txt_file_path = os.path.join(txtpath, name + '.txt')# 解析 XML 文件with open(xml_file_path, 'r') as xml_file:tree = ET.parse(xml_file)root = tree.getroot()w = int(root.find('size').find('width').text) # 圖像寬度h = int(root.find('size').find('height').text) # 圖像高度# 寫入 TXT 文件with open(txt_file_path, 'w') as f_txt:content = ""first = Truefor obj in root.iter('object'):# 獲取類別和邊界框信息class_name = obj.find('name').textclass_num = class_names.index(class_name) # 類別的索引xmlbox = obj.find('bndbox')x1 = int(xmlbox.find('xmin').text)x2 = int(xmlbox.find('xmax').text)y1 = int(xmlbox.find('ymin').text)y2 = int(xmlbox.find('ymax').text)# 轉換為 YOLO 格式x_center = (x1 + x2) / 2 / wy_center = (y1 + y2) / 2 / hwidth = (x2 - x1) / wheight = (y2 - y1) / h# 構建 YOLO 格式的標注行line = f"{class_num} {x_center} {y_center} {width} {height}"content += line if first else f"\n{line}"first = False# 寫入內容到 TXT 文件f_txt.write(content)print(f"已將 {name}.xml 轉換為 {name}.txt")print("轉換完成!")