XML文件转TXT,XML无图片宽高信息
生活随笔
收集整理的這篇文章主要介紹了
XML文件转TXT,XML无图片宽高信息
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
XML文件轉(zhuǎn)TXT,XML無圖片寬高信息
網(wǎng)絡(luò)上有很多xml轉(zhuǎn)txt的文章,不過有的xml文件不包括size信息,即圖片本身的寬高,如先前提到的湛江水下目標(biāo)檢測大賽數(shù)據(jù)集的label文件。因此在前輩的基礎(chǔ)上添加了圖像size的讀取,無需對xml文件進(jìn)行處理,直接將圖片的寬高讀到數(shù)組中,這個方法的局限性在于標(biāo)簽和圖片必須一一對應(yīng),但考慮到數(shù)據(jù)集通常是規(guī)整的,因此無傷大雅。
import xml.etree.ElementTree as ET import os import cv2 from tqdm import tqdmclasses = ["holothurian", "echinus", "scallop", "starfish"] # 類別 xml_path = "xml標(biāo)簽文件夾路徑" txt_path = "txt標(biāo)簽存儲路徑" image_path = "圖像文件夾路徑"# 將原有的xmax,xmin,ymax,ymin換為x,y,w,h def convert(size, box):dw = 1. / size[0]dh = 1. / size[1]x = (box[0] + box[1]) / 2.0y = (box[2] + box[3]) / 2.0w = box[1] - box[0]h = box[3] - box[2]x = x * dww = w * dwy = y * dhh = h * dhreturn (x, y, w, h)# 輸入時圖像和圖像的寬高 def convert_annotation(image_id, width, hight):in_file = open(xml_path + '\\{}.xml'.format(image_id), encoding='UTF-8')out_file = open(txt_path + '\\{}.txt'.format(image_id), 'w') # 生成同名的txt格式文件tree = ET.parse(in_file)root = tree.getroot()size = root.find('size') # 此處是獲取原圖的寬高,便于后續(xù)的歸一化操作if size is not None:w = int(size.find('width').text)h = int(size.find('height').text)else:w = widthh = hightfor obj in root.iter('object'):cls = obj.find('name').text# print(cls)if cls not in classes: # 此處會將cls里沒有的類別打印,以便后續(xù)添加print(cls)continuecls_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)out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')# 此處獲取圖像寬高的數(shù)組,tqdm為進(jìn)度條庫,將處理可視化 def image_size(path):image = os.listdir(path)w_l, h_l = [], []for i in tqdm(image):if i.endswith('jpg'):h_l.append(cv2.imread(os.path.join(path, i)).shape[0])w_l.append(cv2.imread(os.path.join(path, i)).shape[1])return w_l, h_l# 遍歷xml文件,將對應(yīng)的寬高輸入convert_annotation方法 if __name__ == "__main__":img_xmls = os.listdir(xml_path)w, h = image_size(image_path)i = 0for img_xml in img_xmls:label_name = img_xml.split('.')[0]print(label_name)convert_annotation(label_name, w[i], h[i])i += 1總結(jié)
以上是生活随笔為你收集整理的XML文件转TXT,XML无图片宽高信息的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于JavaEE电子邮件系统的设计与实现
- 下一篇: 【告白气球——HTML实现】