1、XML的格式
<annotation><folder>cr</folder><filename>crazing_2.jpg</filename><source><database>NEU-DET</database></source><size><width>200</width><height>200</height><depth>1</depth></size><segmented>0</segmented><object><name>crazing</name><pose>Unspecified</pose><truncated>1</truncated><difficult>0</difficult><bndbox><xmin>99</xmin><ymin>120</ymin><xmax>200</xmax><ymax>174</ymax></bndbox></object><object><name>crazing</name><pose>Unspecified</pose><truncated>1</truncated><difficult>0</difficult><bndbox><xmin>8</xmin><ymin>16</ymin><xmax>200</xmax><ymax>111</ymax></bndbox></object>
</annotation>
我们来读一下这个xml文件核心内容
xmin ymin xmax ymax 这四个值代表了这个图像中的矩形框的位置 并且给这个位置取名为crazing
举个例子 一张有图片
我们用框框把狗框起来 并且命名这个框为 狗
计算机就知道这个地方有个狗
2、转化代码
import xml.etree.ElementTree as ETimport pickle
import os
from os import listdir, getcwd
from os.path import join
import globclasses = ["crazing", "inclusion", "patches", "pitted_surface", "rolled-in_scale", "scratches"]def convert(size, box):dw = 1.0 / size[0]dh = 1.0 / 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_name):in_file = open('./Basic_data/indata/' + image_name[:-3] + 'xml') # xml文件路径out_file = open('./Basic_data/labels/train/' + image_name[:-3] + 'txt', 'w') # 转换后的txt文件存放路径f = open('./Basic_data/indata/' + image_name[:-3] + 'xml')xml_text = f.read()root = ET.fromstring(xml_text)f.close()size = root.find('size')w = int(size.find('width').text)h = int(size.find('height').text)for obj in root.iter('object'):cls = obj.find('name').textif cls not in classes: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')wd = getcwd()if __name__ == '__main__':for image_path in glob.glob("datasets/Basic_data/IMAGES/*.jpg"): # 每一张图片都对应一个xml文件这里写xml对应的图片的路径image_name = image_path.split('\\')[-1]convert_annotation(image_name)
代码中有注释,大家自己理解一下哈
再给大家看一下我的文件结构
大家只要改三个路径 就能运行了
最终 给大家看一下生成的txt文件内容
前面的0代表类别 举个例子 我们检测图片 里面有三个动物 分别是狗 猫 牛那我们就把狗当作0 猫 当作1 牛当作2 这样计算机很容易明白 0后面有四个数字 代表这个类别出现的位置,其实也就是矩形框