import xml.etree.ElementTree as ET
import os, cv2
import numpy as np
from os import listdir
from os.path import join
classes = []
def convert(size, box):
dw = 1. / (size[0])
dh = 1. / (size[1])
# 计算边界框的中心坐标
x = (box[0] + box[2] + box[4] + box[6]) / 4.0
y = (box[1] + box[3] + box[5] + box[7]) / 4.0
# 计算归一化后的宽度和高度
w = max(box[0], box[2], box[4], box[6]) - min(box[0], box[2], box[4], box[6])
h = max(box[1], box[3], box[5], box[7]) - min(box[1], box[3], box[5], box[7])
# 归一化坐标调整
x = x * dw
w = w * dw
y = y * dh
h = h * dh
return (x, y, w, h)
def convert_annotation(xmlpath, xmlname):
with open(xmlpath, "r", encoding='utf-8') as in_file:
txtname = xmlname[:-4] + '.txt'
txtfile = os.path.join(txtpath, txtname)
tree = ET.parse(in_file)
root = tree.getroot()
filename = root.find('filename')
img = cv2.imdecode(np.fromfile('{}/{}.{}'.format(imgpath, xmlname[:-4], postfix), np.uint8), cv2.IMREAD_COLOR)
h, w = img.shape[:2]
res = []
for obj in root.iter('object'):
difficult = obj.find('difficult').text
cls = obj.find('name').text
if cls not in classes:
classes.append(cls)
cls_id = classes.index(cls)
xmlbox = obj.find('bndbox')
x0 = float(xmlbox.find('x0').text)
y0 = float(xmlbox.find('y0').text)
x1 = float(xmlbox.find('x1').text)
y1 = float(xmlbox.find('y1').text)
x2 = float(xmlbox.find('x2').text)
y2 = float(xmlbox.find('y2').text)
x3 = float(xmlbox.find('x3').text)
y3 = float(xmlbox.find('y3').text)
b = (x0, y0, x1, y1, x2, y2, x3, y3)
bb = convert((w, h), b)
res.append(str(cls_id) + " " + " ".join([str(a) for a in bb]))
if len(res) != 0:
with open(txtfile, 'w+') as f:
f.write('\n'.join(res))
if __name__ == "__main__":
postfix = 'png'
imgpath = r'E:\yolov7\dataset\VOC2007_VEDAI\JPEGImages'
xmlpath = r'E:\yolov7\dataset\VOC2007_VEDAI\Annotations'
txtpath = 'VOCdevkit/onetxt'
if not os.path.exists(txtpath):
os.makedirs(txtpath, exist_ok=True)
list = os.listdir(xmlpath)
error_file_list = []
for i in range(0, len(list)):
try:
path = os.path.join(xmlpath, list[i])
if ('.xml' in path) or ('.XML' in path):
convert_annotation(path, list[i])
print(f'file {list[i]} convert success.')
else:
print(f'file {list[i]} is not xml format.')
except Exception as e:
print(f'file {list[i]} convert error.')
print(f'error message:\n{e}')
error_file_list.append(list[i])
print(f'this file convert failure\n{error_file_list}')
print(f'Dataset Classes:{classes}')
【无标题】四点xml
于 2023-10-19 18:59:36 首次发布