关于coco(.json)转voc(.xml)后,object消失的问题

step1 coco转voc代码

此代码借鉴于此博客:link

需要修改的地方

savepath
填写“提取出的类别”保存的地方,会生成两个子文件夹(images、annotations)
datasets_list
修改为自己的存放coco数据集的文件夹的名称
classes_names
修改为自己需要类的名字
dataDir
原coco数据集保存的目录

代码内容

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 = "/home/boni/Downloads/coco_extract/"

img_dir = savepath + 'images/'
anno_dir = savepath + 'Annotations/'
# datasets_list=['train2014', 'val2014']
datasets_list = ['train2017']

# 选择自己的类
classes_names = ['person', 'bicycle', 'car', 'motorcycle', 'bus', 'train', 'traffic', 'fire hydrant', 'stop sign']

# 原数据存储
dataDir = '/home/boni/Downloads/coco_extract'

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>
'''


# if the dir is not exists,make it,else delete it
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):
    # eg:COCO_train2014_000000196610.jpg-->COCO_train2014_000000196610.xml
    anno_path = anno_dir + filename[:-3] + 'xml'
    # img_path = dataDir + dataset + '/' + filename
    img_path = dataDir + '/' + dataset + '/' + filename
    print(img_path)
    dst_imgpath = img_dir + filename

    img = cv2.imread(img_path)
    # if (img.shape[2] == 1):
    #    print(filename + " not a RGB image")
    #   return
    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' % (dataDir, dataset, img['file_name']))
    # Íš¹ýid£¬µÃµœ×¢Ê͵ÄÐÅÏ¢
    annIds = coco.getAnnIds(imgIds=img['id'], catIds=cls_id, iscrowd=None)
    # print(annIds)
    anns = coco.loadAnns(annIds)
    # print(anns)
    # coco.showAnns(anns)
    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:
    # ./COCO/annotations/instances_train2014.json
    annFile = '{}/annotations/instances_{}.json'.format(dataDir, dataset)

    # COCO API for initializing annotated data
    coco = COCO(annFile)

    # show all classes in coco
    classes = id2name(coco)
    print(classes)
    # [1, 2, 3, 4, 6, 8]
    classes_ids = coco.getCatIds(catNms=classes_names)
    print(classes_ids)
    for cls in classes_names:
        # Get ID number of this class
        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)


文档结构显示

文档结构

step2:删除无object项的xml文件及对应的图片

# coding=utf-8
import xml.dom.minidom
import os

# 未连接前xml,images路径
file_path = '/home/boni/Downloads/coco_extract/Annotations/'
img_path = '/home/boni/Downloads/coco_extract/images/'
# 获取路径下所有的xml文档,并保存在列表xml_file中(xml_file是list类型)
xml_file = os.listdir(file_path)
# 获取list长度
# print(len(xml_file))

"""
获取每个元素并与之前的路径连接,对每个xml进行object标签遍历,
xml中有object标签就直接跳过,没有就直接删除对应的xml文档,
并删除JEPGImages下对应的图片
"""
for i in range(len(xml_file)):
    # 连接并保存为新的路径
    new_file_path = os.path.join(file_path, xml_file[i])
    new_img_path = os.path.join(img_path, xml_file[i][:-3]+'jpg')
    # print(new_file_path)
    # print(new_img_path)
    # 打开xml文档
    dom = xml.dom.minidom.parse(new_file_path)
    # 得到文档元素对象
    root = dom.documentElement
    bb = root.getElementsByTagName('object')
    if bb.length == 0:
        # print("no object")
        # 删除无object的xml
        os.remove(new_file_path)
        # print("has remove this xml")
        # 删除无object的xml对应的照片
        os.remove(new_img_path)
        # print("has remove this image")
    else:
        # print("have object")
        print(bb.length)

如有不清楚的地方可关注留言

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: COCO格式的JSON换为VOC格式的XML需要经过以下几个步骤: 第一步,读取COCO格式的JSON文件,解析其中的对象标注数据。一般来说,COCO格式的JSON中每个对象标注都包含类别、边界框位置、标注区域等信息。 第二步,根据解析得到的标注信息,生成VOC格式的XML文件。在生成XML文件时,需要按照VOC格式的要求,设置好文件头和对象标注信息。每个对象标注都需要有其类别、边界框位置、标注区域等信息。 第三步,将生成的VOC格式的XML文件保存到指定路径下。 其中,关于换的实现细节需要注意以下几点: 首先,在解析COCO格式的JSON文件时,需要根据JSON结构中不同的字段和嵌套关系,逐层解析并提取出标注信息。其中,需要注意一些数据格式的换,如COCO格式中的标注区域信息通常是多边形或RLE格式,需要根据VOC格式要求化为矩形。 其次,在生成VOC格式的XML文件时,需要注意文件头的设置,并遵守XML文档的一些规范。例如,每个XML文件都需要有一个根节点,对象标注的信息需要封装在“object”标签中,且标签中的文本内容需要进行编码和义。 最后,在保存XML文件时,需要确保文件目录存在及权限设置正确。此外,还可以为XML文件设置其它元信息,如创建时间、文件格式等。 综上所述,将COCO格式的JSON文件换为VOC格式的XML需要按照一定的规则解析和生成文件,实现上需要注意一些细节。 ### 回答2: 要将COCO格式的JSON文件换为VOC格式的XML文件,需要进行以下步骤: 1.准备好COCO格式的JSON文件和VOC格式的模板XML文件。 2.读取COCO格式的JSON文件,可以使用Python中的json模块来实现。 3.遍历JSON文件中的所有目标,提取出相应的信息,例如目标的类别、位置等。 4.将提取出的信息填写到VOC格式的XML模板中,并保存成XML文件。 5.可以使用Python中的xml.etree.ElementTree模块来实现XML文件的创建和编辑。 6.将换后的XML文件导入到目标检测框架中进行训练和测试。 需要注意的是,COCO格式和VOC格式有很大的差异,因此在换过程中需要特别小心。同时,也需要根据具体的数据集和目标检测框架的要求进行相应的修改和调整。 ### 回答3: COCO (Common Objects in Context)格式是一种常用的目标检测数据集格式,而VOC (Visual Object Classes)格式是另一种经常用于目标检测任务的格式。在实际应用中,有时需要将COCO格式的数据换为VOC格式,以便在某些特定场景中使用。 要将COCO格式JSON换为VOC格式XML,需要进行以下几个步骤: 1. 解析COCO格式JSON数据,获得图片路径、图片大小以及目标检测框的坐标、类别等信息。 2. 根据得到的类别信息,确定VOC格式XML中用于表示目标类别的ID号。 3. 将解析得到的图片大小以及目标框坐标换为VOC格式需要的左上角坐标、右下角坐标等信息。 4. 根据得到的信息,生成VOC格式XML文件。其中,每个目标检测框对应一个对象节点,包含对象的类别、位置等信息。 需要注意的是,COCO格式和VOC格式的差异比较大,对于某些特定的键值对,需要进行相应的换或忽略。此外,在进行数据换时,应注意保留足够的信息,以便后续任务能够顺利进行。 总的来说,将COCO格式JSON换为VOC格式XML需要较为复杂的代码实现,对于没有相关经验的人来说难度较大,建议寻求专业人士的帮助。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值