提取COCO数据集指定类别

安装pycocotools库 

Win11:

pycocotools库下载链接:https://pypi.tuna.tsinghua.edu.cn/simple/pycocotools-windows/

根据自己的python版本和操作系统下载相应的pycocotools

在anaconda环境下cd到上述whl文件的下载路径,用pip安装

命令为:

pip install "pycocotools_windows-2.0-cp38-cp38-win_amd64.whl"  -i https://pypi.tuna.tsinghua.edu.cn/simple/

安装完成后提示:

提取COCO数据集指定类别

1、提取指定类别并将标注信息转换为XML格式

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="/path/to/generate/COCO/" 
img_dir=savepath+'images/'
anno_dir=savepath+'annotations/'
datasets_list=['train2017', 'val2017']

#coco有80类,这里写要提取类的名字,以person为例 
classes_names = ['person'] 
#包含所有类别的原coco数据集路径
'''
目录格式如下:
$COCO_PATH
----|annotations
----|train2017
----|val2017
----|test2017
'''
dataDir= '/path/to/coco_orgi/' 
 
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 not os.path.exists(path):
        os.makedirs(path)  # 可以创建多级目录

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):
    #将图片转为xml,例:COCO_train2017_000000196610.jpg-->COCO_train2017_000000196610.xml
    dst_anno_dir = os.path.join(anno_dir, dataset)
    mkr(dst_anno_dir)
    anno_path=dst_anno_dir + '/' + filename[:-3]+'xml'
    img_path=dataDir+dataset+'/'+filename
    print("img_path: ", img_path)
    dst_img_dir = os.path.join(img_dir, dataset)
    mkr(dst_img_dir)
    dst_imgpath=dst_img_dir+ '/' + filename
    print("dst_imgpath: ", dst_imgpath)
    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_train2017.json
    annFile='{}/annotations/instances_{}.json'.format(dataDir,dataset)
 
    #使用COCO API用来初始化注释数据
    coco = COCO(annFile)
 
    #获取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:
        #获取该类的id
        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)

2、提取指定类别并将标注信息转换为YOLO格式

这里以提取COCOtrain2017数据集的bus类别的图像及标注信息为例

import os
import json
import shutil

# 定义要提取的类别及其新的ID
categories = ['bus', 'bicycle', 'motorcycle']
category_id_map = {'bus': 2, 'bicycle': 3, 'motorcycle': 4}

# 定义数据集路径
data_dir = 'D:/Downloads/dataset/coco/'  # 数据集的根目录

# 定义输出路径
output_dir = 'D:/Downloads/dataset/coco/three_class/'  # 输出目录,用于保存提取后的数据

# 创建输出目录
if not os.path.exists(os.path.join(output_dir, 'annotations')):
    os.makedirs(os.path.join(output_dir, 'annotations'))
    os.makedirs(os.path.join(output_dir, 'images', 'train2017'))
    os.makedirs(os.path.join(output_dir, 'images', 'val2017'))

'''
训练集
'''
# 加载原始instances文件
with open(os.path.join(data_dir, 'annotations', 'instances_train2017.json'), 'r') as f:
    train_instances = json.load(f)

# 筛选指定类别的id
category_ids = {c['id']: category_id_map[c['name']] for c in train_instances['categories'] if c['name'] in categories}
new_categories = [{'id': category_id_map[c['name']], 'name': c['name']} for c in train_instances['categories'] if c['name'] in categories]

# 筛选出包含指定类别的图片id
train_image_ids = set()
new_train_annotations = []
for ann in train_instances['annotations']:
    if ann['category_id'] in category_ids:
        ann['category_id'] = category_ids[ann['category_id']]
        train_image_ids.add(ann['image_id'])
        new_train_annotations.append(ann)

new_images = []
# 复制训练集中包含指定类别的图片到输出目录
for image in train_instances['images']:
    if image['id'] in train_image_ids:
        new_images.append(image)
        shutil.copy(os.path.join(data_dir, 'images', 'train2017', image['file_name']),
                    os.path.join(output_dir, 'images', 'train2017'))

# 构造新的instances文件
new_train_instances = {
    'info': train_instances['info'],
    'licenses': train_instances['licenses'],
    'images': new_images,
    'annotations': new_train_annotations,
    'categories': new_categories
}

# 保存新的instances文件
with open(os.path.join(output_dir, 'annotations', 'instances_train2017.json'), 'w') as f:
    json.dump(new_train_instances, f)

提取后在output_dir下面生成了含有指定类别目标的图像和标注信息,如下所示:

将标注信息转换为YOLO格式

上述代码在annotations文件夹下生成了bus类图像的标注信息,需要再将其转换为YOLO格式的标注信息,转换代码如下所示:

import os
import json
from tqdm import tqdm
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--json_path', default='D:/Downloads/dataset/coco/coco_specific_class/bus/annotations/instances_train2017.json', type=str,
                    help="input: coco format(json)")
parser.add_argument('--save_path', default='D:/Downloads/dataset/coco/coco_specific_class/bus/bus_annotations/', type=str,
                    help="specify where to save the output dir of labels")
arg = parser.parse_args()


def convert(size, box):
    dw = 1. / (size[0])
    dh = 1. / (size[1])
    x = box[0] + box[2] / 2.0
    y = box[1] + box[3] / 2.0
    w = box[2]
    h = box[3]

    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh
    return (x, y, w, h)


if __name__ == '__main__':
    json_file = arg.json_path  # COCO Object Instance 类型的标注
    ana_txt_save_path = arg.save_path  # 保存的路径

    data = json.load(open(json_file, 'r'))
    if not os.path.exists(ana_txt_save_path):
        os.makedirs(ana_txt_save_path)

    id_map = {}  # coco数据集的id不连续!重新映射一下再输出!
    for i, category in enumerate(data['categories']):
        id_map[category['id']] = i

    # 通过事先建表来降低时间复杂度
    max_id = 0
    for img in data['images']:
        max_id = max(max_id, img['id'])
    # 注意这里不能写作 [[]]*(max_id+1),否则列表内的空列表共享地址
    img_ann_dict = [[] for i in range(max_id + 1)]
    for i, ann in enumerate(data['annotations']):
        img_ann_dict[ann['image_id']].append(i)

    for img in tqdm(data['images']):
        filename = img["file_name"]
        img_width = img["width"]
        img_height = img["height"]
        img_id = img["id"]
        head, tail = os.path.splitext(filename)
        ana_txt_name = head + ".txt"  # 对应的txt名字,与jpg一致
        f_txt = open(os.path.join(ana_txt_save_path, ana_txt_name), 'w')
        # 这里可以直接查表而无需重复遍历
        for ann_id in img_ann_dict[img_id]:
            ann = data['annotations'][ann_id]
            box = convert((img_width, img_height), ann["bbox"])
            f_txt.write("%s %s %s %s %s\n" % (id_map[ann["category_id"]], box[0], box[1], box[2], box[3]))
        f_txt.close()

参考链接:

安装pycocotools库_pycocotools库安装-CSDN博客

Python提取COCO数据集中特定的类(亲测有效)_coco数据集提取特定的类-CSDN博客

python提取COCO,VOC数据集中特定的类_coco数据集提取自己需要的类-CSDN博客

coco 2017数据集 类别提取并转换为yolo数据集_coco2017-CSDN博客

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值