import xml.etree.ElementTree as ET
import os
classes = ["钓鱼"]
def convert(size, box):
dw = 1. / (size[0])
dh = 1. / (size[1])
x_max = box[0] + box[2]
y_max = box[1] + box[3]
x = (box[0] + x_max) / 2.0
y = (box[1] + y_max) / 2.0
x = x * dw
w = box[2] * dw
y = y * dh
h = box[3] * dh
return x, y, w, h ##最后返回的坐标是中心点坐标的比例,宽高的比例。
def convert_annotation(image_id, in_file, out_file):
txt_file = open(out_file + '/%s.txt' % (image_id), 'w')
try:
xml_file = open(in_file + '/%s.xml' % (image_id), encoding='UTF-8')
tree = ET.parse(xml_file)
except:
return
root = tree.getroot()
size = root.find('size')
w = float(size.find('width').text)
h = float(size.find('height').text)
try:
for obj in root.iter('object'):
cls = obj.find('name').text
if cls in classes:
cls_id = classes.index(cls)
xmlbox = obj.find('bndbox')
b = (float(xmlbox.find('xmin').text), float(xmlbox.find('ymin').text), float(xmlbox.find('xmax').text),
float(xmlbox.find('ymax').text))
b1, b2, b3, b4 = b
# 标注越界修正
if b3 > w:
b2 = w
if b4 > h:
b4 = h
b = (b1, b2, b3-b1, b4-b2) ##把x,y,w,h转化成yolo标签格式
bb = convert((w, h), b)
txt_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
else:
print("label not in classes")
print(cls)
except:
print("no obj")
return
imageDir = 'data/images'
xml_file = 'data/xml'
out_file = 'data/txt'
img_ids = os.listdir(imageDir)
for img_id in img_ids:
image_id = img_id.strip('.jpg')
convert_annotation(image_id, xml_file, out_file)
xml转txt脚本
最新推荐文章于 2023-11-06 13:56:51 发布