将COCO数据集转换为VOC数据集

将COCO数据集转换为VOC数据集,将本代码跟coco2017放在同一目录下,下载COCO官方数据集,直接运行即可,不需要做任何改动。
在这里插入图片描述
在这里插入图片描述

'''
把coco数据集合的所有标注转换到voc格式,不改变图片命名方式,
注意,原来有一些图片是黑白照片,检测出不是 RGB 图像,这样的图像不会被放到新的文件夹中
'''
from pycocotools.coco import COCO
import os, cv2, shutil
from lxml import etree, objectify
from tqdm import tqdm
from PIL import Image

# 生成图片保存的路径
CKimg_dir = './coco2017_voc/images'
# 生成标注文件保存的路径
CKanno_dir = './coco2017_voc/annotations'


# 若模型保存文件夹不存在,创建模型保存文件夹,若存在,删除重建
def mkr(path):
    if os.path.exists(path):
        shutil.rmtree(path)
        os.mkdir(path)
    else:
        os.mkdir(path)


def save_annotations(filename, objs, filepath):
    annopath = CKanno_dir + "/" + filename[:-3] + "xml"  # 生成的xml文件保存路径
    dst_path = CKimg_dir + "/" + filename
    img_path = filepath
    img = cv2.imread(img_path)
    im = Image.open(img_path)
    if im.mode != "RGB":
        print(filename + " not a RGB image")
        im.close()
        return
    im.close()
    shutil.copy(img_path, dst_path)  # 把原始图像复制到目标文件夹
    E = objectify.ElementMaker(annotate=False)
    anno_tree = E.annotation(
        E.folder('1'),
        E.filename(filename),
        E.source(
            E.database('CKdemo'),
            E.annotation('VOC'),
            E.image('CK')
        ),
        E.size(
            E.width(img.shape[1]),
            E.height(img.shape[0]),
            E.depth(img.shape[2])
        ),
        E.segmented(0)
    )
    for obj in objs:
        E2 = objectify.ElementMaker(annotate=False)
        anno_tree2 = E2.object(
            E.name(obj[0]),
            E.pose(),
            E.truncated("0"),
            E.difficult(0),
            E.bndbox(
                E.xmin(obj[2]),
                E.ymin(obj[3]),
                E.xmax(obj[4]),
                E.ymax(obj[5])
            )
        )
        anno_tree.append(anno_tree2)
    etree.ElementTree(anno_tree).write(annopath, pretty_print=True)


def showbycv(coco, dataType, img, classes, origin_image_dir, verbose=False):
    filename = img['file_name']
    filepath = os.path.join(origin_image_dir, dataType, filename)
    I = cv2.imread(filepath)
    annIds = coco.getAnnIds(imgIds=img['id'], iscrowd=None)
    anns = coco.loadAnns(annIds)
    objs = []
    for ann in anns:
        name = classes[ann['category_id']]
        if 'bbox' in ann:
            bbox = ann['bbox']
            xmin = (int)(bbox[0])
            ymin = (int)(bbox[1])
            xmax = (int)(bbox[2] + bbox[0])
            ymax = (int)(bbox[3] + bbox[1])
            obj = [name, 1.0, xmin, ymin, xmax, ymax]
            objs.append(obj)
            if verbose:
                cv2.rectangle(I, (xmin, ymin), (xmax, ymax), (255, 0, 0))
                cv2.putText(I, name, (xmin, ymin), 3, 1, (0, 0, 255))
    save_annotations(filename, objs, filepath)
    if verbose:
        cv2.imshow("img", I)
        cv2.waitKey(0)


def catid2name(coco):  # 将名字和id号建立一个字典
    classes = dict()
    for cat in coco.dataset['categories']:
        classes[cat['id']] = cat['name']
        # print(str(cat['id'])+":"+cat['name'])
    return classes


def get_CK5(origin_anno_dir, origin_image_dir, verbose=False):
    dataTypes = ['val2017']
    for dataType in dataTypes:
        annFile = 'instances_{}.json'.format(dataType)
        annpath = os.path.join(origin_anno_dir, annFile)
        coco = COCO(annpath)
        classes = catid2name(coco)
        imgIds = coco.getImgIds()
        # imgIds=imgIds[0:1000]#测试用,抽取10张图片,看下存储效果
        for imgId in tqdm(imgIds):
            img = coco.loadImgs(imgId)[0]
            showbycv(coco, dataType, img, classes, origin_image_dir, verbose=False)


def main():
    base_dir = './coco2017_voc'  # step1 这里是一个新的文件夹,存放转换后的图片和标注
    image_dir = os.path.join(base_dir, 'images')  # 在上述文件夹中生成images,annotations两个子文件夹
    anno_dir = os.path.join(base_dir, 'annotations')
    mkr(image_dir)
    mkr(anno_dir)
    origin_image_dir = './coco2017'  # step 2原始的coco的图像存放位置
    origin_anno_dir = './coco2017/annotations'  # step 3 原始的coco的标注存放位置
    print(origin_anno_dir)
    verbose = True  # 是否需要看下标记是否正确的开关标记,若是true,就会把标记展示到图片上
    get_CK5(origin_anno_dir, origin_image_dir, verbose)


if __name__ == "__main__":
    main()
  • 4
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
你可以使用以下步骤将COCO数据集转换VOC格式: 1. 下载COCO数据集:首先,你需要从COCO官方网站下载COCO数据集。你可以选择下载训练集(train2017)和验证集(val2017),以及相应的标注文件。 2. 安装cocoapi:你需要安装Python的cocoapi库来处理COCO数据集。可以通过以下命令安装: ```shell pip install cython git clone https://github.com/cocodataset/cocoapi.git cd cocoapi/PythonAPI python setup.py build_ext install ``` 3. 下载VOCdevkit:VOC数据集结构与COCO略有不同,你需要创建一个类似的目录结构。你可以从VOC官方网站下载VOC数据集的开发工具包(VOCdevkit),解压缩后得到一个名为`VOCdevkit`的文件夹。 4. 创建VOC标注文件:使用cocoapi库将COCO标注文件转换VOC格式。你可以使用以下Python代码: ```python from pycocotools.coco import COCO import os import cv2 import xml.etree.ElementTree as ET def coco_to_voc(coco_annotation_file, output_dir): coco = COCO(coco_annotation_file) categories = coco.loadCats(coco.getCatIds()) category_dict = {category['id']: category['name'] for category in categories} image_ids = coco.getImgIds() for image_id in image_ids: img_info = coco.loadImgs(image_id)[0] img_path = os.path.join('path/to/coco/images', img_info['file_name']) img = cv2.imread(img_path) xml_root = ET.Element("annotation") ET.SubElement(xml_root, "folder").text = "VOCdevkit/VOC2007/JPEGImages" ET.SubElement(xml_root, "filename").text = img_info['file_name'] size = ET.SubElement(xml_root, "size") ET.SubElement(size, "width").text = str(img.shape[1]) ET.SubElement(size, "height").text = str(img.shape[0]) ET.SubElement(size, "depth").text = str(img.shape[2]) ann_ids = coco.getAnnIds(imgIds=img_info['id']) annotations = coco.loadAnns(ann_ids) for annotation in annotations: category = category_dict[annotation['category_id']] xmin, ymin, width, height = annotation['bbox'] xmax = xmin + width ymax = ymin + height obj = ET.SubElement(xml_root, "object") ET.SubElement(obj, "name").text = category bndbox = ET.SubElement(obj, "bndbox") ET.SubElement(bndbox, "xmin").text = str(int(xmin)) ET.SubElement(bndbox, "ymin").text = str(int(ymin)) ET.SubElement(bndbox, "xmax").text = str(int(xmax)) ET.SubElement(bndbox, "ymax").text = str(int(ymax)) xml_tree = ET.ElementTree(xml_root) xml_tree.write(os.path.join(output_dir, f"{img_info['file_name'][:-4]}.xml")) coco_annotation_file = 'path/to/coco/annotations/instances_train2017.json' output_dir = 'path/to/VOCdevkit/VOC2007/Annotations' coco_to_voc(coco_annotation_file, output_dir) ``` 请确保替换`coco_annotation_file`和`output_dir`变量的路径为你自己的路径。 5. 拷贝图像文件:将COCO图像文件复制到VOC数据集的图像文件夹中。假设你已经将COCO图像文件放在了`path/to/coco/images`目录下,可以使用以下命令将它们复制到VOC数据集的图像文件夹中: ```shell cp path/to/coco/images/* path/to/VOCdevkit/VOC2007/JPEGImages/ ``` 6. 生成图像列表:在VOC数据集的ImageSets/Main文件夹中,创建一个名为`train.txt`的文本文件,并列出训练图像的文件名(不包含文件扩展名)。例如,如果你有两个训练图像`image1.jpg`和`image2.jpg`,则`train.txt`应包含以下内容: ``` image1 image2 ``` 完成上述步骤后,你应该已经成功将COCO数据集转换VOC格式。现在你可以使用VOC格式的数据进行目标检测等任务。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值