VOC格式转COCO格式

导读

个人学习笔记
有些开源的算法数据集用的是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'))
  • 1
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以使用一些工具和代码来将VOC格式的数据换为COCO格式,以便在mmdetection中使用。以下是一种可能的方法: 1. 首先,确保你已经安装了`mmcv`和`mmdet`库。你可以使用以下命令安装它们: ``` pip install mmcv-full mmdet ``` 2. 下载并解压VOC数据集,并将其组织为以下结构: ``` VOCdevkit/ ├── VOC2007 │ ├── Annotations │ ├── ImageSets │ └── JPEGImages └── VOC2012 ├── Annotations ├── ImageSets └── JPEGImages ``` 3. 创建一个Python脚本,例如`voc2coco.py`,并使用以下代码来进行VOCCOCO格式换: ```python import os import json from xml.etree.ElementTree import Element, SubElement, tostring from xml.dom.minidom import parseString def parse_voc_annotation(ann_dir, img_dir, labels=[]): # 读取VOC标注文件和图像文件夹 ann_files = sorted(os.listdir(ann_dir)) img_files = sorted(os.listdir(img_dir)) assert len(ann_files) == len(img_files), "Number of annotation files doesn't match number of image files" # 构建COCO格式标注数据结构 coco_data = { "images": [], "annotations": [], "categories": [] } category_id = 0 for i, ann_file in enumerate(ann_files): img_file = img_files[i] img_id = i + 1 # 解析VOC标注文件 ann_path = os.path.join(ann_dir, ann_file) tree = parseString(open(ann_path).read()) root = tree.documentElement # 获取图像信息 img_width = int(root.getElementsByTagName("width")[0].childNodes[0].data) img_height = int(root.getElementsByTagName("height")[0].childNodes[0].data) img_name = img_file.split(".")[0] # 添加图像信息到coco_data["images"] coco_data["images"].append({ "file_name": img_file, "height": img_height, "width": img_width, "id": img_id }) # 解析VOC标注信息 objects = root.getElementsByTagName("object") for obj in objects: name = obj.getElementsByTagName("name")[0].childNodes[0].data if name not in labels: labels.append(name) category_id = labels.index(name) + 1 bbox = obj.getElementsByTagName("bndbox")[0] xmin = int(bbox.getElementsByTagName("xmin")[0].childNodes[0].data) ymin = int(bbox.getElementsByTagName("ymin")[0].childNodes[0].data) xmax = int(bbox.getElementsByTagName("xmax")[0].childNodes[0].data) ymax = int(bbox.getElementsByTagName("ymax")[0].childNodes[0].data) width = xmax - xmin height = ymax - ymin # 添加标注信息到coco_data["annotations"] coco_data["annotations"].append({ "image_id": img_id, "category_id": category_id, "bbox": [xmin, ymin, width, height], "area": width * height, "iscrowd": 0, "id": len(coco_data["annotations"]) + 1 }) # 构建coco_data["categories"] for i, label in enumerate(labels): coco_data["categories"].append({ "id": i + 1, "name": label, "supercategory": "object" }) return coco_data if __name__ == '__main__': ann_dir = 'VOCdevkit/VOC2007/Annotations' img_dir = 'VOCdevkit/VOC2007/JPEGImages' labels = [] coco_data = parse_voc_annotation(ann_dir, img_dir, labels) # 保存为COCO格式的JSON文件 with open('annotations.json', 'w') as f: json.dump(coco_data, f) ``` 4. 运行`voc2coco.py`脚本,它将生成一个名为`annotations.json`的COCO格式标注文件。 现在,你可以使用这个生成的COCO格式的标注文件在mmdetection中进行训练或评估。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值