yolov10 voc标注转txt
时间: 2025-03-16 11:11:15 浏览: 56
### 转换 YOLOv10 的 VOC 标注格式为 TXT 文件
YOLO 系列模型通常使用 `.txt` 格式的标注文件作为训练数据的一部分,而 VOC 数据集采用的是 XML 格式。为了将 VOC 格式的标注转换为适用于 YOLOv10 的 `.txt` 格式,可以按照以下方法实现。
#### 方法概述
VOC 格式的标注存储在 XML 文件中,其中包含了对象类别、边界框坐标等信息。要将其转换为 YOLO 格式,需提取这些信息并重新计算边界框的中心点和宽高比例[^1]。以下是具体操作:
---
#### 1. 提取 XML 中的信息
XML 文件中的关键字段包括 `filename`, `width`, `height`, 和 `<object>` 下的子节点如 `name`, `bndbox` (包含 `xmin`, `ymin`, `xmax`, `ymax`)。通过解析 XML 文件获取上述信息后,可进一步完成格式转换。
```python
import xml.etree.ElementTree as ET
def parse_voc_xml(xml_file):
tree = ET.parse(xml_file)
root = tree.getroot()
image_size = {
'width': int(root.find('size').find('width').text),
'height': int(root.find('size').find('height').text)
}
objects = []
for obj in root.findall('object'):
name = obj.find('name').text
bnd_box = obj.find('bndbox')
bbox = [
float(bnd_box.find('xmin').text),
float(bnd_box.find('ymin').text),
float(bnd_box.find('xmax').text),
float(bnd_box.find('ymax').text)
]
objects.append({'name': name, 'bbox': bbox})
return image_size, objects
```
---
#### 2. 将边界框转换为 YOLO 格式
YOLO 使用相对坐标表示边界框位置 `(xc, yc, w, h)`,分别代表中心点横纵坐标以及宽度高度的比例值。可以通过以下公式进行转换:
\[
xc = \frac{x_{max} + x_{min}}{2W}, \quad yc = \frac{y_{max} + y_{min}}{2H}
\]
\[
w = \frac{x_{max} - x_{min}}{W}, \quad h = \frac{y_{max} - y_{min}}{H}
\]
其中 \( W \) 和 \( H \) 是图像的宽度和高度。
```python
def convert_bbox_to_yolo(image_size, bbox):
width, height = image_size['width'], image_size['height']
xmin, ymin, xmax, ymax = bbox
xc = ((xmax + xmin) / 2) / width
yc = ((ymax + ymin) / 2) / height
w = (xmax - xmin) / width
h = (ymax - ymin) / height
return [xc, yc, w, h]
```
---
#### 3. 编写完整的转换脚本
下面是一个完整的 Python 脚本用于批量转换 VOC 格式的 XML 文件到 YOLO 格式的 TXT 文件。
```python
import os
from pathlib import Path
class_name_map = {'cat': 0, 'dog': 1} # 替换为目标类别的映射表
def voc_to_yolo(voc_dir, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for xml_file in Path(voc_dir).glob("*.xml"):
txt_path = os.path.join(output_dir, f"{xml_file.stem}.txt")
image_size, objects = parse_voc_xml(str(xml_file))
with open(txt_path, "w") as f:
for obj in objects:
class_id = class_name_map[obj['name']]
yolo_coords = convert_bbox_to_yolo(image_size, obj['bbox'])
line = f"{class_id} {' '.join(map(lambda x: str(round(x, 6)), yolo_coords))}\n"
f.write(line)
if __name__ == "__main__":
voc_annotations_dir = "./annotations" # 存储 XML 文件的路径
yolo_labels_dir = "./labels" # 输出 TXT 文件的目标路径
voc_to_yolo(voc_annotations_dir, yolo_labels_dir)
```
---
#### 注意事项
- **类别索引映射**:需要提前定义好目标类别的名称及其对应的整数 ID 映射关系。
- **空白标签处理**:如果某些 XML 文件为空白或者不包含任何对象,则应跳过该文件或将对应 TXT 文件留空[^2]。
- **工具支持**:也可以借助 LabelImg 工具手动调整或验证生成的结果[^4]。
---
### 总结
以上流程展示了如何从 VOC 格式的 XML 注解文件转换至适合 YOLO 训练使用的 TXT 文件形式。此过程涉及读取 XML 结构化数据、执行必要的数学运算以适配新标准,并最终保存结果于指定目录下。
阅读全文
相关推荐


















