coco2017数据标签格式转到VOC2007格式

2023-05-16

以下代码是将coco2017数据集标签格式转到voc2007格式的代码.

# -*- coding: utf-8 -*-
from pycocotools.coco import COCO
import os
import shutil
from tqdm import tqdm
import skimage.io as io
import matplotlib.pyplot as plt
import cv2
from PIL import Image, ImageDraw

savepath = "coco2017toVOC2007/"
datasets_list = ['train2017']  ##运行完之后再改为val2017再运行一次
img_dir = savepath + 'images_train/'  #####这个路径会把你处理的图片拷贝进来,这里只处理了train2017文件夹下的数据,所以处理好之后需要修改生成image文件夹的名称为train2017
anno_dir = savepath + 'annotations_train/'  # 当前目录下会生成annotations文件夹存放xml,结束后修改名称
# classes_names = ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
#                  'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
#                  'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase',
#                  'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard',
#                  'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
#                  'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake',
#                  'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
#                  'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock',
#                  'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush']
classes_names = ['traffic light']
dataDir = 'COCO2017'  ####### 连接到coco的数据集
headstr = """\
<annotation>
    <folder>VOC</folder>
    <filename>%s</filename>
    <source>
        <database>My Database</database>
        <annotation>COCO</annotation>
        <image>flickr</image>
        <flickrid>NULL</flickrid>
    </source>
    <owner>
        <flickrid>NULL</flickrid>
        <name>company</name>
    </owner>
    <size>
        <width>%d</width>
        <height>%d</height>
        <depth>%d</depth>
    </size>
    <segmented>0</segmented>
"""
objstr = """\
    <object>
        <name>%s</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>%d</xmin>
            <ymin>%d</ymin>
            <xmax>%d</xmax>
            <ymax>%d</ymax>
        </bndbox>
    </object>
"""

tailstr = '''\
</annotation>
'''


def mkr(path):
    if os.path.exists(path):
        shutil.rmtree(path)
        os.mkdir(path)
    else:
        os.mkdir(path)


mkr(img_dir)
mkr(anno_dir)


def id2name(coco):
    classes = dict()
    for cls in coco.dataset['categories']:
        classes[cls['id']] = cls['name']
    return classes


def write_xml(anno_path, head, objs, tail):
    f = open(anno_path, "w")
    f.write(head)
    for obj in objs:
        f.write(objstr % (obj[0], obj[1], obj[2], obj[3], obj[4]))
    f.write(tail)


def save_annotations_and_imgs(coco, dataset, filename, objs):
    anno_path = anno_dir + filename[:-3] + 'xml'
    print('anno_path:%s' % anno_path)
    # img_path=dataDir+'/'+'images'+'/'+dataset+'/'+filename
    img_path = dataDir + '/' + dataset + '/' + filename
    print('img_path:%s' % img_path)
    print('step3-image-path-OK')
    dst_imgpath = img_dir + filename

    img = cv2.imread(img_path)
    '''if (img.shape[2] == 1):
        print(filename + " not a RGB image")     
        return'''
    print('img_path:%s' % img_path)
    print('dst_imgpath:%s' % dst_imgpath)
    shutil.copy(img_path, dst_imgpath)

    head = headstr % (filename, img.shape[1], img.shape[0], img.shape[2])
    tail = tailstr
    write_xml(anno_path, head, objs, tail)


def showimg(coco, dataset, img, classes, cls_id, show=True):
    global dataDir
    # I=Image.open('%s/%s/%s/%s'%(dataDir,'images',dataset,img['file_name']))
    I = Image.open('%s/%s/%s' % (dataDir, dataset, img['file_name']))  ########may be you can changed
    annIds = coco.getAnnIds(imgIds=img['id'], catIds=cls_id, iscrowd=None)
    anns = coco.loadAnns(annIds)
    objs = []
    for ann in anns:
        class_name = classes[ann['category_id']]
        if class_name in classes_names:
            print(class_name)
            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 = [class_name, xmin, ymin, xmax, ymax]
                objs.append(obj)
                # draw = ImageDraw.Draw(I)
                # draw.rectangle([xmin, ymin, xmax, ymax])
    # if show:
    # plt.figure()
    # plt.axis('off')
    # plt.imshow(I)
    # plt.show()
    return objs


for dataset in datasets_list:
    annFile = '{}/annotations/instances_{}.json'.format(dataDir, dataset)  # 存放json文件的路径
    print('annFile:%s' % annFile)
    coco = COCO(annFile)
    '''
    loading annotations into memory...
    Done (t=0.81s)
    creating index...
    index created!
    '''
    classes = id2name(coco)
    print("classes:%s" % classes)
    classes_ids = coco.getCatIds(catNms=classes_names)
    print(classes_ids)
    for cls in classes_names:
        cls_id = coco.getCatIds(catNms=[cls])
        img_ids = coco.getImgIds(catIds=cls_id)
        print(cls, len(img_ids))
        # imgIds=img_ids[0:10]
        for imgId in tqdm(img_ids):
            img = coco.loadImgs(imgId)[0]
            filename = img['file_name']
            # print(filename)
            objs = showimg(coco, dataset, img, classes, classes_ids, show=False)
            # print(objs)
            save_annotations_and_imgs(coco, dataset, filename, objs)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

coco2017数据标签格式转到VOC2007格式 的相关文章

随机推荐

  • 关于ST-Link V2 报错internal commend error的处理办法

    1 检查相关配置是否正确 确定接线没有问题 xff1a Vcc 接 Vcc GND 接 GND SWCLK 接 SWCLK SWDIO 接 SWDIO 首先 xff0c 确保电脑的CH驱动已经安装成功且正常运行 判断方法 xff1a 点击设
  • docker容器技术基础入门及LXC的配置

    docker容器技术基础入门及LXC的配置 1 docker简介1 2 容器与虚拟化的区别 xff1a 1 3 docker的三个基本概念1 3 1镜像1 3 2 分层储存1 3 3 容器1 3 4 仓库 2 docker产生的背景2 1
  • 简单易懂的51单片机LCD1602显示protues仿真程序

    时序图 仿真效果 include 34 AT89X51 h 34 typedef unsigned char u8 typedef unsigned int u16 define lcd1602 DB P3 sbit RS 61 P2 5
  • html5的思维导图--超详细

    下面是最近我学习总结的学习思维导图
  • 2023年天梯赛(l1 - l2全部题解)(第十二届)

    span class token macro property span class token directive hash span span class token directive keyword include span spa
  • c语言strtok函数完美实现

    看到网上好多错误的strtok实现 xff0c 也不能说错 xff0c 准确的说是没有完全的实现strtok xff0c 现自己写了下 xff0c 目前还没有找到bug xff0c 如果有不对的欢迎指出 大多数网上的strtok实现的代码跑
  • 使用vscode操作本地git

    学习目标 xff1a 使用vscode操作本地git 基础的git的命令 使用本地git进行版本穿梭 修改本地git的用户名和邮箱 git有三个状态 xff1a 工作区 暂存区 版本库 使用vscode操作本地git xff1a 1 首先
  • Linux环境下安装Docker

    1 安装Docker 1 1在linux系统中下载前置环境 1 安装wget命令 wget命令是Linux系统用于从Web下载文件的命令行工具 2 安装依赖环境 3 设置Docker镜像源 xff0c 因为默认的服务器很慢所以我选择国内镜像
  • VOC2007数据标签格式转COCO2017格式

    以下代码是将voc2007的数据标签格式转为coco2017数据标签格式 可直接基于voc2007的 xml所有文件进行处理 也可先转化为 txt文件路径之后再处理 此处我是直接基于 xml所有文件进行处理的 span class toke
  • SQLyog连接MYSQL时报错 Client does not support authentication protocol requested by server; consider upgra

    之前安装MYSQL8 0的时候安装的是绿色版 xff0c 在cmd中配置完所有参数之后 xff0c 在连接SQLyog的时候却报出了以下错误 翻译一下大致的意思为 xff1a 客户端不支持服务器请求的身份验证协议 xff1b 考虑升级MYS
  • 图神经网络对抗攻击的研究学习(一)

    目录 0 引入1 初窥1 1 图神经网络1 1 1 传统神经网络的不足1 1 2 图神经网络概况1 1 3 Graph Convolution Networks GCN 1 1 4 Graph Attention Networks GAT
  • 二叉树遍历方法——前、中、后序遍历(图解)

    目录 一 前序遍历 xff08 1 xff09 递归版本 xff08 2 xff09 非递归版本 二 中序遍历 xff08 1 xff09 递归版本 xff08 2 xff09 非递归版本 三 后序遍历 xff08 1 xff09 递归版本
  • VMware虚拟机安装Linux

    前言 接下来要分享一些Linux相关的内容 咱们来聊聊为啥要学Linux 首先 xff0c 运维靠这个吃饭 xff0c 测试要部署测试环境 大部分企业要用到Linux操作系统 xff0c 作为开发多少也要会是吧 所以 xff0c 他来了 一
  • MPU6050基本原理介绍及程序配置

    一 MPU6050简介 1 内部主要结构 xff1a 陀螺仪 加速度计 数字运动处理器DMP xff08 Digital Motion Processor xff09 PS MPU6050还含有第二IIC接口 xff0c 用于连接一个 第三
  • 2023年河北省天梯赛C语言 猜帽子游戏

    include lt stdio h gt int N K x int a 100 void solve int dui 61 0 int cuo 61 0 int mzuo 61 0 for int i 61 0 i lt N i 43
  • 树莓派4B环境配置

    前言 最近要用到树莓派 xff0c 荔枝整理了一份基础的树莓派4B配置总结 xff0c 有需要的大家自取 文章目录 前言 一 基础配置 1 1 烧录 1 2 进入桌面 1 3 开启SSH和VNC 二 更换国内源 三 查看python3版本并
  • Python之列表的基本操作

    目录 1 列表的创建与遍历 2 添加元素 3 删除元素 4 分片赋值 5 列表排序 完整代码 xff1a 本文的代码体为一个完整体 xff0c 即最开始的列表的创建与遍历中创建的列表 xff0c 为后续操作的主列表 如需从总体观看全部代码
  • Qt 实现简单的tcp网络通信

    文章目录 成品效果图 xff1a 代码 xff1a 工具头文件tool hUI文件代码 ui widget h 窗口头文件 widget h xff1a 窗口源文件widget cpp 相关代码说明 xff1a Qt获取本机ip Qt 打开
  • VNC可实现屏幕共享

    第一步 第二歩 第三步第四步 第五步 第六步 第七步
  • coco2017数据标签格式转到VOC2007格式

    以下代码是将coco2017数据集标签格式转到voc2007格式的代码 span class token operator span span class token operator span span class token opera