rolableimg旋转框和lableimg的标注框比,它可以更好的贴合目标,但两者的xml文件稍微有些不同,不想手动标记可以用代码直接转换。转换的过程中需要注意的是旋转框中多了一个angle的标签,angle是弧度,范围在(0,π)。
我使用的是最小外接矩阵,求出了矩形框的中心坐标、宽、高和角度。需求相同可以照抄。
import xml.etree.ElementTree as ET
import os
import math
# 假设 xml_file_path 是你的 XML 文件路径
xml_file_path = 'xml文件路径'
# 解析 XML 文件
tree = ET.parse(xml_file_path)
root = tree.getroot()
# 用于跟踪元素与其父元素关系的字典
parent_map = {root: None}
# 遍历整棵树以建立元素到其父元素的映射
def build_parent_map(node, parent):
parent_map[node] = parent
for child in node:
build_parent_map(child, node)
# 构建父元素映射
build_parent_map(root, None)
# 遍历所有 object 元素,并检查 name 属性
for obj in root.findall('.//object'):
name_elem = obj.find('name')
if name_elem is not None and name_elem.text != 'tcjyz':
# 从父元素中删除 object 元素
parent = parent_map[obj]
if parent is not None:
parent.remove(obj)
for elem in root.iter():
if elem.tag == 'score':
# 修改标签名为'robndbox'
elem.tag = 'type'
elem.text='robndbox'
# 检查元素的标签名是否为'bndbox'
if elem.tag == 'bndbox':
# 修改标签名为'robndbox'
elem.tag = 'robndbox'
xmin_elem = elem.find('xmin')
if xmin_elem is not None:
xmin_elem.tag = 'cx'
xmin_elem.text = str(center[0]) # 旋转框中心坐标x的值
# 查找并修改ymin元素的值
ymin_elem = elem.find('ymin')
if ymin_elem is not None:
ymin_elem.tag = 'cy'
ymin_elem.text = str(center[1]) # 旋转框中心坐标y的值
# 查找并修改xmax元素的值
xmax_elem = elem.find('xmax')
if xmax_elem is not None:
xmax_elem.tag = 'w'
xmax_elem.text = str(w) # 旋转框的宽
# 查找并修改ymax元素的值
ymax_elem = elem.find('ymax')
if ymax_elem is not None:
ymax_elem.tag = 'h'
ymax_elem.text = str(h) # 旋转框的高
angle_elem = ET.Element('angle')
angle1 = angle / (180 / math.pi)
angle_elem.text = str(angle1) # 替换 'new_angle_value' 为你想要的角度值
# 将 'angle' 元素添加到 'robndbox' 元素中
elem.append(angle_elem)
# 将修改后的 XML 树转换回字符串
modified_xml_string = ET.tostring(root, encoding='utf-8').decode('utf-8')
# 构造修改后的 XML 文件路径
filename = os.path.basename(xml_file_path)
directory = os.path.dirname(xml_file_path)
modified_filename = '/raid/Xinru/modified_1' + filename
modified_xml_path = os.path.join(directory, modified_filename)
# 将修改后的 XML 写入文件
with open(modified_xml_path, 'w', encoding='utf-8') as f:
f.write(modified_xml_string)
print(f"修改后的 XML 已保存至: {modified_xml_path}")#保存路径