dior数据集转化yolo格式
时间: 2025-03-16 17:17:27 浏览: 100
### 将 DIOR 数据集转换为 YOLO 格式
为了将 DIOR 数据集转换为 YOLO 格式,可以按照以下方法实现。DIOR 数据集通常以 XML 文件形式存储标注信息[^4],而 YOLO 格式的标注文件是以 `.txt` 形式存储的,并且每行包含目标的类别编号及其边界框坐标。
#### 转换逻辑说明
1. **解析 XML 文件**:通过 Python 的 `xml.etree.ElementTree` 或其他库来解析 DIOR 数据集中每个图像对应的 XML 文件。
2. **提取标注信息**:从 XML 中提取对象的目标名称、边界框坐标(xmin, ymin, xmax, ymax),以及图片尺寸(width, height)。
3. **计算 YOLO 坐标格式**:YOLO 使用归一化的中心点坐标和宽高比例 (xc, yc, w, h),因此需要基于图片尺寸对边界框进行转换。
4. **映射类别名到 ID**:创建一个字典 `class_name_to_id` 来将 DIOR 数据集中的类别名映射为连续的整数 ID。
5. **保存为 TXT 文件**:将上述信息写入对应图像同名的 `.txt` 文件中。
以下是具体实现代码:
```python
import os
import xml.etree.ElementTree as ET
def convert_dior_to_yolo(dior_xml_dir, output_txt_dir, class_name_to_id):
"""
将 DIOR 数据集的 XML 标注文件转换为 YOLO 格式。
参数:
dior_xml_dir (str): 存储 DIOR 数据集 XML 文件的目录路径。
output_txt_dir (str): 输出 YOLO 格式标注文件的目录路径。
class_name_to_id (dict): 类别名到类别的映射字典。
"""
if not os.path.exists(output_txt_dir):
os.makedirs(output_txt_dir)
for xml_file in os.listdir(dior_xml_dir):
if not xml_file.endswith('.xml'):
continue
tree = ET.parse(os.path.join(dior_xml_dir, xml_file))
root = tree.getroot()
image_width = int(root.find('size/width').text)
image_height = int(root.find('size/height').text)
txt_content = []
for obj in root.findall('object'):
name = obj.find('name').text.strip()
if name not in class_name_to_id:
print(f"Warning: Unknown class {name} found in file {xml_file}. Skipping...")
continue
class_id = class_name_to_id[name]
bndbox = obj.find('bndbox')
xmin = float(bndbox.find('xmin').text)
ymin = float(bndbox.find('ymin').text)
xmax = float(bndbox.find('xmax').text)
ymax = float(bndbox.find('ymax').text)
xc = ((xmin + xmax) / 2) / image_width
yc = ((ymin + ymax) / 2) / image_height
w = (xmax - xmin) / image_width
h = (ymax - ymin) / image_height
txt_line = f"{class_id} {xc:.6f} {yc:.6f} {w:.6f} {h:.6f}"
txt_content.append(txt_line)
with open(os.path.join(output_txt_dir, xml_file.replace('.xml', '.txt')), 'w') as f:
f.write('\n'.join(txt_content))
# 定义类别映射表
dior_class_names = [
"airplane", "airport", "baseballfield", "basketballcourt",
"bridge", "chimney", "expressway-service-area", "expressway-toll-station"
# 添加更多类别...
]
class_name_to_id = {name: idx for idx, name in enumerate(dior_class_names)}
convert_dior_to_yolo(
dior_xml_dir="path/to/dior/xmls",
output_txt_dir="path/to/output/txts",
class_name_to_id=class_name_to_id
)
```
此脚本会遍历指定的 XML 文件夹并将它们逐一转换为 YOLO 格式的标注文件。注意需调整 `dior_class_names` 列表以匹配实际使用的 DIOR 数据集版本。
---
#### 注意事项
- 如果 DIOR 数据集未提供完整的类别列表,请手动补充至 `dior_class_names` 变量中。
- 确保输入路径 (`dior_xml_dir`) 和输出路径 (`output_txt_dir`) 正确无误。
- 对于训练、验证和测试集的划分,可参考 VOC 至 YOLO 转换的经验[^2],编写额外的脚本来完成数据切分操作。
---
阅读全文
相关推荐














