共计 1942 个字符,预计需要花费 5 分钟才能阅读完成。
在目标检测任务中,数据标注格式的统一至关重要。本文将带你一步步完成从 anti-uav-rgbt 数据集到 YOLO 格式的转换,特别适合刚入门计算机视觉的新手。

1. 理解标注格式差异
anti-uav-rgbt 数据集通常采用 PASCAL VOC 格式的 XML 标注,而 YOLO 需要的是简单的 TXT 文本格式。两者的核心区别在于:
- VOC XML 格式:
- 使用绝对坐标(像素值)
- 包含图片尺寸等元数据
-
结构化的标签层级
-
YOLO TXT 格式:
- 使用归一化的相对坐标(0- 1 之间)
- 每行一个对象:
类别 ID x_center y_center width height - 没有图片尺寸信息
转换的主要目的是为了适配 YOLO 系列模型的训练需求。
2. 完整 Python 转换脚本
下面是一个完整的转换脚本,我们拆解关键部分来看:
import os
import xml.etree.ElementTree as ET
import cv2
def convert_annotation(xml_path, img_dir, output_dir):
# 解析 XML 文件
tree = ET.parse(xml_path)
root = tree.getroot()
# 获取图片尺寸
img_path = os.path.join(img_dir, root.find('filename').text)
img = cv2.imread(img_path)
img_h, img_w = img.shape[:2]
# 准备写入 TXT 文件
txt_path = os.path.join(output_dir, os.path.splitext(root.find('filename').text)[0] + '.txt')
with open(txt_path, 'w') as f:
for obj in root.iter('object'):
try:
# 类别名称转 ID(根据你的数据集调整)cls_name = obj.find('name').text
cls_id = 0 if cls_name == 'drone' else 1
# 获取边界框坐标
bbox = obj.find('bndbox')
xmin = float(bbox.find('xmin').text)
ymin = float(bbox.find('ymin').text)
xmax = float(bbox.find('xmax').text)
ymax = float(bbox.find('ymax').text)
# 计算归一化后的中心点和宽高
x_center = ((xmin + xmax) / 2) / img_w
y_center = ((ymin + ymax) / 2) / img_h
width = (xmax - xmin) / img_w
height = (ymax - ymin) / img_h
# 写入 TXT 文件
f.write(f"{cls_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\n")
except Exception as e:
print(f"Error processing {xml_path}: {e}")
continue
# 批量处理函数
def batch_convert(xml_dir, img_dir, output_dir):
os.makedirs(output_dir, exist_ok=True)
for xml_file in os.listdir(xml_dir):
if xml_file.endswith('.xml'):
convert_annotation(os.path.join(xml_dir, xml_file), img_dir, output_dir)
3. 避坑指南
在实际转换过程中,有几个关键点需要特别注意:
宽高计算的取整问题
- 绝对坐标转相对坐标时,建议保留足够的小数位数(如 6 位)
- 避免过早的四舍五入,否则可能影响边界框精度
多目标场景的文件写入优化
- 使用
with open() as f上下文管理器确保文件正确关闭 - 不要在循环内反复打开 / 关闭同一个文件
类别 ID 的映射策略
- 建立明确的类别名称到 ID 的映射关系
- 建议使用字典存储映射关系,便于维护
class_mapping = {'drone': 0, 'bird': 1, 'plane': 2}
4. 延伸思考
完成基础转换后,可以进一步思考以下问题:
-
视频序列标注的连续性:如何处理视频中目标的连续性问题?可以考虑添加帧 ID 或使用跟踪算法关联目标
-
小目标检测的标注优化:对于小目标,是否需要在标注时适当扩大边界框?或者采用特殊的标注策略
-
自动化校验方法:如何自动检查转换后的标注是否正确?可以开发可视化工具,或计算转换前后的 IOU 差异
通过这个过程,我们不仅完成了格式转换,更重要的是理解了不同标注格式的设计思想。希望这篇指南能帮助你顺利开始目标检测的实践之旅!
正文完
