VOC转换为COCO数据集出错

利用swin transformer官方代码中提供的格式转换代码进行转换

img


结果发现转换之后的COCO数据集下的坐标和和VOC格式下的坐标值不一致
1、VOC数据集

img

2、转换后的COCO数据集

img


为什么转换之后的坐标不一致呀

你确定这两个是同一个图片的标签?
你第一图里面就一个检测框数据,为什么到了第二图就多个了?检查一下文件名或者其他路径问题,看下是哪里设置出问题了

如果在将VOC数据集转换为COCO数据集时,发现坐标不一致,可以尝试以下解决方案:

  1. 检查VOC数据集中的坐标是否正确,可以通过可视化工具查看标注框是否正确。

  2. 检查转换代码中的坐标转换是否正确,比如是否将VOC数据集中的坐标从左上角改为中心点坐标。

  3. 如果转换代码中使用了resize操作,需要确保resize后的图像和标注框坐标是一致的。

  4. 如果VOC数据集中的坐标是相对于整张图像的,而COCO数据集中的坐标是相对于裁剪后的图像的,需要进行相应的坐标转换。

以下是一个可能的解决方案,可以将VOC数据集中的坐标从左上角改为中心点坐标:

import xml.etree.ElementTree as ET
import json
import os

def voc2coco(xml_path, save_path):
    classes = ['person', 'car', 'bus'] # 根据实际情况修改类别名称和数量
    data_dict = {
        "images": [],
        "annotations": [],
        "categories": []
    }
    for i, cls in enumerate(classes):
        data_dict['categories'].append({
            'id': i + 1,
            'name': cls,
            'supercategory': cls
        })

    ann_id = 1
    img_id = 1
    for xml_file in os.listdir(xml_path):
        tree = ET.parse(os.path.join(xml_path, xml_file))
        root = tree.getroot()

        filename = root.find('filename').text
        width = int(root.find('size').find('width').text)
        height = int(root.find('size').find('height').text)

        data_dict['images'].append({
            'id': img_id,
            'file_name': filename,
            'width': width,
            'height': height
        })

        for obj in root.findall('object'):
            cls = obj.find('name').text
            bbox = obj.find('bndbox')
            x1 = int(bbox.find('xmin').text)
            y1 = int(bbox.find('ymin').text)
            x2 = int(bbox.find('xmax').text)
            y2 = int(bbox.find('ymax').text)
            x_center = (x1 + x2) / 2
            y_center = (y1 + y2) / 2
            w = x2 - x1
            h = y2 - y1

            data_dict['annotations'].append({
                'id': ann_id,
                'image_id': img_id,
                'category_id': classes.index(cls) + 1