voc2yolo脚本
时间: 2025-01-22 17:58:12 浏览: 58
### 将VOC格式转换为YOLO格式的Python脚本
为了实现从Pascal VOC到YOLO格式的数据集转换,可以编写如下所示的Python脚本来完成此操作。该过程涉及读取XML文件中的边界框坐标并将其重新计算为中心点(x_center, y_center),宽度(width)以及高度(height)[^1]。
```python
import os
from xml.etree import ElementTree as ET
def convert_voc_to_yolo(xml_file_path, output_dir, image_width, image_height):
tree = ET.parse(xml_file_path)
root = tree.getroot()
with open(os.path.join(output_dir, os.path.basename(xml_file_path).replace('.xml', '.txt')), 'w') as f:
for obj in root.findall('object'):
label = obj.findtext('name')
bndbox = obj.find('bndbox')
xmin = int(bndbox.findtext('xmin'))
ymin = int(bndbox.findtext('ymin'))
xmax = int(bndbox.findtext('xmax'))
ymax = int(bndbox.findtext('ymax'))
x_center = (xmin + xmax) / 2.0 / image_width
y_center = (ymin + ymax) / 2.0 / image_height
width = abs(xmax - xmin) / image_width
height = abs(ymax - ymin) / image_height
line = " ".join([str(label), str(x_center), str(y_center), str(width), str(height)])
f.write(line + '\n')
if __name__ == '__main__':
# 假设图像尺寸固定已知
img_wdith = 800
img_height = 600
voc_xml_files_directory = './Annotations' # 存储原始标注文件(.xml)的位置
destination_folder_for_txts = './labels' # 转换后的标签保存位置
if not os.path.exists(destination_folder_for_txts):
os.makedirs(destination_folder_for_txts)
for file_name in os.listdir(voc_xml_files_directory):
if file_name.endswith(".xml"):
full_file_path = os.path.join(voc_xml_files_directory, file_name)
convert_voc_to_yolo(full_file_path, destination_folder_for_txts, img_wdith, img_height)
```
上述代码片段展示了如何遍历给定目录下的所有`.xml`文件,并逐一对它们执行转换逻辑。需要注意的是,在实际应用中可能还需要考虑类别名称映射等问题。
阅读全文
相关推荐


















