VOC格式转COCO格式

文章介绍了如何将使用VOC格式标注的数据集转换为COCO格式,以适应使用COCO格式的开源算法。首先,整理VOC数据集的训练集和验证集,包括XML标注文件和JPEG图片。然后,通过Python脚本将XML标注文件按训练集和验证集分类,并合并成一个JSON文件。转换过程涉及文件的复制和XML到JSON的结构转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

导读

个人学习笔记
有些开源的算法数据集用的是coco格式,我们用标注软件标注自己的数据时,可能会按VOC格式来标注,这时候为了适配开源算法,就需把VOC转COCO格式。

VOC数据集

做目标检测时候需用到的VOC文件如下图:
在这里插入图片描述
JPEGImage中装的是图片
在这里插入图片描述
Anonotations中装的是图片对应的标注:
如下图5张这种图片中有一把椅子。
在这里插入图片描述

COCO数据集

下图是将VOC转coco后的格式,coco数据集的图片跟VOC是一样的,但是他的标注全部放在一个annotations文件中的单一json文件中
在这里插入图片描述
而不是一张图片,一个标注文件。
在这里插入图片描述

转换

首先获取VOC数据集的训练集跟验证集,这个训练集跟验证集可以按自己要求去划分。VOC数据集中的Imageset文件里有划分好的txt文件,这边直接拿划分好的来演示:
在这里插入图片描述

将训练集和验证集所有标注文件(xml格式)放到一个文件夹下面:
根据划分好的train.txt跟text.text文件将train跟val的编号跟他们对应的xml文件放到ann_train跟ann_val文件夹里
在这里插入图片描述
在这里插入图片描述
将训练集和验证集所有图片文件(jpg格式)放到一个文件夹下面:
根据txt文件里的train跟val的编号,将对应的jpg文件放到train_voc跟val_voc文件夹里
在这里插入图片描述
在这里插入图片描述

代码如下:
根据数据源的位置,去重新修改def init(self):下的内容。

import os
import shutil


# the path is you original file directory
# the newpath is the new directory
class BatchCopy():
    def __init__(self):
        self.path = r'E:\deeplearnning-project\VOCdevkit\VOC2007\Annotations'  ####voc是将所有xml文件都放在同一目录下
        self.image_path = r'E:\deeplearnning-project\VOCdevkit\VOC2007\JPEGImages'####voc的图片位置
        self.newpath = r'E:\deeplearnning-project\voc2coco\ann_val'  ####将训练集的xml文件单独放一个目录
        self.newiamge_path = r'E:\deeplearnning-project\voc2coco\val_voc'####voc转coco后的图片分类位置
        self.txt = r'E:\deeplearnning-project\voc2coco\2007_val.txt' ###训练集或验证集的txt文件位置

    def copy_file(self):
        if not os.path.exists(self.newpath):
            os.makedirs(self.newpath)
        else:
            shutil.rmtree(self.newpath)
        if not os.path.exists(self.newiamge_path):
            os.makedirs(self.newiamge_path)



        filelist = os.listdir(self.path)  # file list in this directory
        # print(len(filelist))
        test_list = loadFileList(self.txt)
        # print(len(test_list))
        for f in filelist:
            filedir = os.path.join(self.path, f)
            (shotname, extension) = os.path.splitext(f)
            if str(shotname) in test_list:
                filedir_image = os.path.join(self.image_path, shotname) + '.jpg'
                # print('success')
                shutil.copyfile(str(filedir_image),os.path.join(self.newiamge_path,shotname)+'.jpg')
                shutil.copyfile(str(filedir), os.path.join(self.newpath, f))


# load the list of train/test file list
def loadFileList(txt):
    filelist = []
    f = open(txt)  
    lines = f.readlines()
    for line in lines:
        line = line.strip('\r\n')  # to remove the '\n' for test.txt, '\r\n' for tainval.txt
        line = str(line)
        line = os.path.basename(line)

        _, file_suffix = os.path.splitext(line)
        filelist.append(_)

    f.close()
    # print(filelist)
    return filelist


if __name__ == '__main__':
    demo = BatchCopy()
    demo.copy_file()

这时候已经完成coco格式里图片分类成训练集跟验证集的工作了:
在这里插入图片描述
最后一步,将标注里的一堆训练集或验证集的xml文件合并改写成一个json文件:

在这里插入图片描述
ann_train跟ann_val文件夹里的xml文件转成coco的json模式
代码如下: 只要改动main里的内容即刻

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

coco = dict()
coco['images'] = []
coco['type'] = 'instances'
coco['annotations'] = []
coco['categories'] = []

category_set = dict()
image_set = set()

category_item_id = -1
image_id = 20180000000
annotation_id = 0


def addCatItem(name):
    global category_item_id
    category_item = dict()
    category_item['supercategory'] = 'none'
    category_item_id += 1
    category_item['id'] = category_item_id
    category_item['name'] = name
    coco['categories'].append(category_item)
    category_set[name] = category_item_id
    return category_item_id


def addImgItem(file_name, size):
    global image_id
    if file_name is None:
        raise Exception('Could not find filename tag in xml file.')
    if size['width'] is None:
        raise Exception('Could not find width tag in xml file.')
    if size['height'] is None:
        raise Exception('Could not find height tag in xml file.')
    image_id += 1
    image_item = dict()
    image_item['id'] = image_id
    image_item['file_name'] = file_name
    image_item['width'] = size['width']
    image_item['height'] = size['height']
    coco['images'].append(image_item)
    image_set.add(file_name)
    return image_id


def addAnnoItem(object_name, image_id, category_id, bbox):
    global annotation_id
    annotation_item = dict()
    annotation_item['segmentation'] = []
    seg = []
    # bbox[] is x,y,w,h
    # left_top
    seg.append(bbox[0])
    seg.append(bbox[1])
    # left_bottom
    seg.append(bbox[0])
    seg.append(bbox[1] + bbox[3])
    # right_bottom
    seg.append(bbox[0] + bbox[2])
    seg.append(bbox[1] + bbox[3])
    # right_top
    seg.append(bbox[0] + bbox[2])
    seg.append(bbox[1])

    annotation_item['segmentation'].append(seg)

    annotation_item['area'] = bbox[2] * bbox[3]
    annotation_item['iscrowd'] = 0
    annotation_item['ignore'] = 0
    annotation_item['image_id'] = image_id
    annotation_item['bbox'] = bbox
    annotation_item['category_id'] = category_id
    annotation_id += 1
    annotation_item['id'] = annotation_id
    coco['annotations'].append(annotation_item)


def parseXmlFiles(xml_path):
    for f in os.listdir(xml_path):
        if not f.endswith('.xml'):
            continue

        bndbox = dict()
        size = dict()
        current_image_id = None
        current_category_id = None
        file_name = None
        size['width'] = None
        size['height'] = None
        size['depth'] = None

        xml_file = os.path.join(xml_path, f)
        print(xml_file)

        tree = ET.parse(xml_file)
        root = tree.getroot()
        if root.tag != 'annotation':
            raise Exception('pascal voc xml root element should be annotation, rather than {}'.format(root.tag))

        # elem is <folder>, <filename>, <size>, <object>
        for elem in root:
            current_parent = elem.tag
            current_sub = None
            object_name = None

            if elem.tag == 'folder':
                continue

            if elem.tag == 'filename':
                file_name = elem.text
                if file_name in category_set:
                    raise Exception('file_name duplicated')

            # add img item only after parse <size> tag
            elif current_image_id is None and file_name is not None and size['width'] is not None:
                if file_name not in image_set:
                    current_image_id = addImgItem(file_name, size)
                    print('add image with {} and {}'.format(file_name, size))
                else:
                    raise Exception('duplicated image: {}'.format(file_name))
                    # subelem is <width>, <height>, <depth>, <name>, <bndbox>
            for subelem in elem:
                bndbox['xmin'] = None
                bndbox['xmax'] = None
                bndbox['ymin'] = None
                bndbox['ymax'] = None

                current_sub = subelem.tag
                if current_parent == 'object' and subelem.tag == 'name':
                    object_name = subelem.text
                    if object_name not in category_set:
                        current_category_id = addCatItem(object_name)
                    else:
                        current_category_id = category_set[object_name]

                elif current_parent == 'size':
                    if size[subelem.tag] is not None:
                        raise Exception('xml structure broken at size tag.')
                    size[subelem.tag] = int(subelem.text)

                # option is <xmin>, <ymin>, <xmax>, <ymax>, when subelem is <bndbox>
                for option in subelem:
                    if current_sub == 'bndbox':
                        if bndbox[option.tag] is not None:
                            raise Exception('xml structure corrupted at bndbox tag.')
                        bndbox[option.tag] = int(option.text)

                # only after parse the <object> tag
                if bndbox['xmin'] is not None:
                    if object_name is None:
                        raise Exception('xml structure broken at bndbox tag')
                    if current_image_id is None:
                        raise Exception('xml structure broken at bndbox tag')
                    if current_category_id is None:
                        raise Exception('xml structure broken at bndbox tag')
                    bbox = []
                    # x
                    bbox.append(bndbox['xmin'])
                    # y
                    bbox.append(bndbox['ymin'])
                    # w
                    bbox.append(bndbox['xmax'] - bndbox['xmin'])
                    # h
                    bbox.append(bndbox['ymax'] - bndbox['ymin'])
                    print('add annotation with {},{},{},{}'.format(object_name, current_image_id, current_category_id,
                                                                   bbox))
                    addAnnoItem(object_name, current_image_id, current_category_id, bbox)


if __name__ == '__main__':
	# 只需要改动这两个参数就行了
    xml_path = r'E:\deeplearnning-project\voc2coco\ann_val'  # 这是xml文件所在的地址
    json_file = r'E:\deeplearnning-project\voc2coco\val.json'  # 这是你要生成的json文件
    parseXmlFiles(xml_path) 
    json.dump(coco, open(json_file, 'w'))
要将VOC格式的数据集换为COCO格式,可以按照以下步骤进行操作: 1. 首先,将VOC数据集中的Annotations文件夹里的文件按照训练集和验证集分别放在两个文件夹中。这样可以方便后续的处理。 2. 接下来,将这两个文件夹中的XML文件换成COCO数据集的JSON格式。你可以使用相应的工具或者脚本来完成这个换过程。这个换过程会将XML文件中的标注信息提取出来,并按照COCO数据集的格式进行组织和保存。 3. 换完成后,你将得到两个JSON文件,分别对应训练集和验证集。这些JSON文件包含了每个图像的信息、标注框的位置和类别等相关信息。 通过以上步骤,你就成功地将VOC数据集换为了COCO格式,方便后续使用effcientdet等网络进行训练和应用。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [将VOC格式的数据集换为COCO格式,xml格式换成json格式](https://download.youkuaiyun.com/download/qq_28257631/85131545)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [voc数据集coco数据集](https://blog.youkuaiyun.com/jinjieingbiubiu/article/details/125385906)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值