FCOS训练自己的数据?从Labelme标注到VOC格式转换,这份避坑指南请收好
FCOS训练自定义数据集从Labelme标注到VOC格式的完整避坑指南当你已经用Labelme完成了图像标注却卡在数据格式转换这一步时这篇文章将成为你的救星。FCOS作为一款优秀的全卷积目标检测模型对输入数据格式有着严格的要求而官方文档往往不会详细告诉你如何从零开始准备数据。本文将手把手带你走过这段充满陷阱的旅程。1. 理解FCOS的数据需求FCOS默认支持两种数据格式COCO和VOC。对于大多数自定义数据集场景VOC格式更为简单直接。但问题在于Labelme生成的JSON标注文件与VOC的XML格式完全不同这就是我们需要跨越的第一道鸿沟。VOC格式的核心目录结构如下dataset/ ├── Annotations/ # 存放XML标注文件 ├── ImageSets/ # 存放训练/验证/测试集划分文件 │ ├── Main/ │ │ ├── train.txt │ │ ├── val.txt │ │ └── test.txt └── JPEGImages/ # 存放原始图像文件关键差异点Labelme使用相对坐标0-1之间而VOC使用绝对像素坐标Labelme的JSON结构更自由VOC XML有严格的字段要求Labelme支持多边形标注而FCOS通常只需要矩形框2. 从Labelme JSON到VOC XML的转换实战转换过程的核心是提取Labelme JSON中的关键信息并按照VOC XML的格式重新组织。以下是一个Python脚本示例可以批量完成这个转换import json import os import xml.etree.ElementTree as ET from xml.dom import minidom def labelme_to_voc(json_path, output_dir, class_mapping): # 读取Labelme JSON文件 with open(json_path, r) as f: data json.load(f) # 创建XML根节点 annotation ET.Element(annotation) # 添加基本信息 folder ET.SubElement(annotation, folder) folder.text VOC2007 filename ET.SubElement(annotation, filename) filename.text os.path.basename(data[imagePath]) size ET.SubElement(annotation, size) width ET.SubElement(size, width) width.text str(data[imageWidth]) height ET.SubElement(size, height) height.text str(data[imageHeight]) depth ET.SubElement(size, depth) depth.text 3 # 假设是RGB图像 # 处理每个标注对象 for shape in data[shapes]: if shape[shape_type] ! rectangle: continue # FCOS通常只需要矩形框 obj ET.SubElement(annotation, object) name ET.SubElement(obj, name) name.text class_mapping.get(shape[label], shape[label]) # 其他必要字段 ET.SubElement(obj, pose).text Unspecified ET.SubElement(obj, truncated).text 0 ET.SubElement(obj, difficult).text 0 # 边界框坐标 bndbox ET.SubElement(obj, bndbox) points shape[points] xmin str(min(points[0][0], points[1][0])) ymin str(min(points[0][1], points[1][1])) xmax str(max(points[0][0], points[1][0])) ymax str(max(points[0][1], points[1][1])) ET.SubElement(bndbox, xmin).text xmin ET.SubElement(bndbox, ymin).text ymin ET.SubElement(bndbox, xmax).text xmax ET.SubElement(bndbox, ymax).text ymax # 美化XML输出 rough_string ET.tostring(annotation, utf-8) reparsed minidom.parseString(rough_string) pretty_xml reparsed.toprettyxml(indent ) # 保存XML文件 xml_filename os.path.splitext(os.path.basename(json_path))[0] .xml xml_path os.path.join(output_dir, xml_filename) with open(xml_path, w) as f: f.write(pretty_xml) # 使用示例 class_mapping {cat: cat, dog: dog} # 可选的标签映射 output_dir Annotations os.makedirs(output_dir, exist_okTrue) for json_file in os.listdir(labelme_jsons): if json_file.endswith(.json): labelme_to_voc( os.path.join(labelme_jsons, json_file), output_dir, class_mapping )常见陷阱及解决方案坐标溢出问题Labelme允许标注框超出图像边界但VOC格式不允许解决方法在转换时对坐标进行裁剪xmin max(0, min(points[0][0], points[1][0])) ymin max(0, min(points[0][1], points[1][1])) xmax min(data[imageWidth], max(points[0][0], points[1][0])) ymax min(data[imageHeight], max(points[0][1], points[1][1]))标签名称不一致不同标注人员可能使用不同的大小写或缩写建议建立统一的标签映射表图像路径问题Labelme JSON中的imagePath可能是相对路径确保图像能被正确找到或者统一复制到JPEGImages目录3. 构建完整的VOC数据集结构转换完标注文件只是第一步接下来需要组织完整的VOC数据集结构。以下是关键步骤创建标准目录结构mkdir -p dataset/{Annotations,ImageSets/Main,JPEGImages}移动文件到正确位置将转换好的XML文件放入Annotations目录将原始图像文件放入JPEGImages目录确保文件名一致仅扩展名不同生成ImageSet划分文件 通常需要将数据集划分为训练集、验证集和测试集。以下是一个简单的划分脚本import os import random # 获取所有图像文件名不带扩展名 image_names [os.path.splitext(f)[0] for f in os.listdir(JPEGImages) if f.endswith(.jpg)] random.shuffle(image_names) # 划分比例 total len(image_names) train_ratio 0.7 val_ratio 0.15 test_ratio 0.15 train_end int(total * train_ratio) val_end train_end int(total * val_ratio) # 写入文件 def write_to_file(names, filepath): with open(filepath, w) as f: f.write(\n.join(names)) write_to_file(image_names[:train_end], ImageSets/Main/train.txt) write_to_file(image_names[train_end:val_end], ImageSets/Main/val.txt) write_to_file(image_names[val_end:], ImageSets/Main/test.txt)重要检查点确保每个XML文件都有对应的图像文件检查标注框是否合理没有负坐标或超出图像边界验证类别名称的一致性4. FCOS配置适配你的数据集数据准备好了接下来需要告诉FCOS如何读取你的数据。这涉及到几个关键配置文件修改paths_catalog.py 找到fcos/FCOS/fcos_core/config/paths_catalog.py添加你的数据集DATASETS { # ... 其他数据集配置 voc_2007: { data_dir: your_dataset_path, split: train }, voc_2007_custom_train: { img_dir: your_dataset_path/JPEGImages, ann_file: your_dataset_path/Annotations, split: train }, voc_2007_custom_val: { img_dir: your_dataset_path/JPEGImages, ann_file: your_dataset_path/Annotations, split: val } }更新类别定义 修改fcos/FCOS/fcos_core/data/datasets/voc.py中的CLASSESCLASSES ( __background__, your_class_1, your_class_2, # ... 你的其他类别 )调整模型配置 在训练配置文件中如fcos_imprv_R_50_FPN_1x.yaml更新类别数MODEL: FCOS: NUM_CLASSES: 5 # 包括背景类常见错误排查类别数不匹配会导致训练失败路径错误会导致数据加载失败VOC格式不正确会导致标注无法解析5. 验证数据是否正确加载在开始长时间训练前先验证数据是否正确加载可视化检查 修改demo脚本检查标注框是否正确显示from fcos_core.data.datasets import VOCDataset import matplotlib.pyplot as plt dataset VOCDataset( your_dataset_path/JPEGImages, your_dataset_path/Annotations, ImageSets/Main/train.txt, transformsNone ) # 可视化第一个样本 img, target, _ dataset[0] plt.imshow(img) for box in target.bbox: plt.gca().add_patch(plt.Rectangle( (box[0], box[1]), box[2]-box[0], box[3]-box[1], fillFalse, edgecolorr, linewidth2 )) plt.show()数据加载性能检查 确保数据加载不会成为训练瓶颈python -m torch.distributed.launch --nproc_per_node1 tools/train_net.py \ --config-file configs/fcos/fcos_imprv_R_50_FPN_1x.yaml \ --skip-test \ DATALOADER.NUM_WORKERS 4 \ OUTPUT_DIR output/debug如果一切正常你应该能看到训练开始并且损失值在逐步下降。如果遇到问题最常见的根源还是数据格式问题回到前面的步骤仔细检查。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2616003.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!