提取COCO数据集中特定的类—vehicle 4类
- 1 安装pycocotools
- 2 下载COCO数据集
- 3 提取特定的类别
- 4 多类标签合并
1 安装pycocotools
pycocotools github地址
pip install git+https://github.com/philferriere/cocoapi.git#subdirectory=PythonAPI
2 下载COCO数据集
COCO官网下载2017 Train images,2017 Val images
文件目录结构如下
data/
├── COCO
│ ├── annotations_trainval2017
│ │ ├── annotations
│ │ │ ├── instances_train2017.json
│ │ │ ├── captions_val2017.json
│ ├── train2017
├── getVehicleFromCOCO.py
├── coco_car
├── coco_bus
├── coco_truck
├── coco_train
3 提取特定的类别
创建coco_car、coco_bus、coco_truck、coco_train
四个文件夹,依次修改savepath
为以上文件夹名称,classes_names
修改为car、bus、truck、train,分别将四类车辆存到对应的文件夹。
提取特定的类别getVehicleFromCOCO.py
代码如下:
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#the path you want to save your results for coco to voc
savepath="coco_car" #保存提取类的路径
img_dir=savepath+'images/'
anno_dir=savepath+'Annotations/'
datasets_list=['train2017']
classes_names = ['car'] #要提取类的名字
dataDir= 'COCO/' #原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>
'''#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 classesdef 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.xmlanno_path=anno_dir+filename[:-3]+'xml'img_path=dataDir+dataset+'/'+filenameprint(img_path)dst_imgpath=img_dir+filenameimg=cv2.imread(img_path)#if (img.shape[2] == 1):# print(filename + " not a RGB image")# returnshutil.copy(img_path, dst_imgpath)head=headstr % (filename, img.shape[1], img.shape[0], img.shape[2])tail = tailstrwrite_xml(anno_path,head, objs, tail)def showimg(coco,dataset,img,classes,cls_id,show=True):global dataDirI=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 objsfor dataset in datasets_list:#./COCO/annotations/instances_train2014.jsonannFile='{}/annotations/instances_{}.json'.format(dataDir,dataset)#COCO API for initializing annotated datacoco = COCO(annFile)#show all classes in cococlasses = 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 classcls_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)
4 多类标签合并
创建以下四个文件夹,将coco_car
中的图像拷贝到JPEGImages
,标注文件拷贝到Annotations
。
执行以下脚本生成ImageSets/train.txt
import sys
import os
folder = "JPEGImages"
voc_train_txt = "ImageSets/train.txt"
file_voc = open(voc_train_txt, 'w',encoding="utf-8")
file_tree = os.walk(folder)
for path, _, files in file_tree:for file in files:name, ext = os.path.splitext(file)file_voc.write(name+'\n')
执行以下脚本将Annotations
中的xml文件转换成txt,存储在labels
文件夹中。
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import joinsets=[('2024', 'train')]
classes = ["car","bus","truck","train"]def convert(size, box):dw = 1./size[0]dh = 1./size[1]x = (box[0] + box[1])/2.0y = (box[2] + box[3])/2.0w = box[1] - box[0]h = box[3] - box[2]x = x*dww = w*dwy = y*dhh = h*dhreturn (x,y,w,h)def convert_annotation(image_id):in_file = open('Annotations/%s.xml'%(image_id),"r",encoding="utf-8")#以追加的方式生成txt,这样4类中的重复图像的标签就会合并out_file = open('labels/%s.txt'%(image_id), 'a',encoding="utf-8")print( "imd id: %s " %(image_id))tree=ET.parse(in_file)root = tree.getroot()size = root.find('size')w = int(size.find('width').text)h = int(size.find('height').text)for obj in root.iter('object'):if obj.find('difficult'):difficult = obj.find('difficult').textelse:difficult = 0cls = obj.find('name').textif cls not in classes or int(difficult) == 1:print( "%s has wrong label: %s " %(in_file, cls)) # ignore difficult valuecontinuecls_id = classes.index(cls)xmlbox = obj.find('bndbox')b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text))bb = convert((w,h), b)out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')in_file.close()out_file.close()wd = getcwd()
for year, image_set in sets:if not os.path.exists('labels/'):os.makedirs('labels/')image_ids = open('ImageSets/%s.txt'%(image_set)).read().strip().split()#print(image_ids)for image_id in image_ids:convert_annotation(image_id)#image_ids.close()
再将coco_bus、coco_truck、coco_train
按照coco_car
相同的方式生成标签,最终不同类别中重复图像的不同类标签就会合并,再将图像拷贝到同一文件夹去重即可。
参考文章:
(1) python提取COCO,VOC数据集中特定的类
(2) philferriere/cocoapi