import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
import glob
classes = ["crazing", "inclusion", "patches", "pitted_surface", "rolled-in_scale", "scratches"]
def convert(size, box):
dw = 1./size[0]
dh = 1./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):
in_file = open('./ANNOTATIONS/'+image_name[:-3]+'xml')
out_file = open('./LABELS/'+image_name[:-3]+'txt','w')
tree=ET.parse(in_file)
root = tree.getroot()
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').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)
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("./IMAGES/*.jpg"):
image_name = image_path.split('\\')[-1]
#print(image_path)
convert_annotation(image_name)
1. 定义目标类别
classes = ["crazing", "inclusion", "patches", "pitted_surface", "rolled-in_scale", "scratches"]
这一行代码定义了感兴趣的类别列表,即那些我们希望在训练模型时识别的物体类别。
2. 坐标转换函数
def convert(size, box):
dw = 1./size[0]
dh = 1./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)
convert
函数将传入的边界框坐标(xmin, xmax, ymin, ymax)转换为归一化的中心点坐标和宽高。这是因为大多数深度学习模型都使用归一化的坐标系统。
3. 注释转换函数
def convert_annotation(image_name):
in_file = open('./ANNOTATIONS/'+image_name[:-3]+'xml')
out_file = open('./LABELS/'+image_name[:-3]+'txt','w')
tree = ET.parse(in_file)
root = tree.getroot()
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').text
if cls not in classes:
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)
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
这个函数处理一个图像的XML标注文件,解析图像中每个对象的坐标,使用convert
函数转换坐标,并将结果写入新的文本文件中。
4. 处理所有图像文件
if __name__ == '__main__':
for image_path in glob.glob("./IMAGES/*.jpg"):
image_name = image_path.split('\\')[-1]
convert_annotation(image_name)