本文主要是介绍python提取COCO数据集中特定的类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
记录一下提取Coco自行车类别的过程
1.安装pycocotools github地址:https://github.com/philferriere/cocoapi
pip install git+https://github.com/philferriere/cocoapi.git#subdirectory=PythonAPI
2.提取其中的bicycle类的代码如下:
需要修改的地方
savepath
datasets_list
classes_names
dataDir
使用的这篇博客中的代码
https://blog.csdn.net/weixin_38632246/article/details/97141364
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="/media/deepnorth/14b6945d-9936-41a8-aeac-505b96fc2be8/COCO/"img_dir=savepath+'images/'
anno_dir=savepath+'Annotations/'
# datasets_list=['train2014', 'val2014']
datasets_list=['train2014']#这里填写需要提取的类别,本人此处提取bicycle
classes_names = ['bicycle'] #原coco数据集的目录
dataDir= '/media/deepnorth/14b6945d-9936-41a8-aeac-505b96fc2be8/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)
COCO数据集2014
代码执行完之后会生成对应的 images文件夹和 Annotations(.xml)文件夹
有了这两个文件就可以利用voc的代码转换为yolo目标检测的txt标签文件
相关代码
需要修改的参数
classes
data_path
list_file
in_file
out_file
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import joinclasses = ["bicycle"]def convert(size, box):dw = 1./(size[0])dh = 1./(size[1])x = (box[0] + box[1])/2.0 - 1y = (box[2] + box[3])/2.0 - 1w = 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('coco_voc_val/Annotations/%s.xml'%(image_id))out_file = open('coco_voc_val/labels/%s.txt'%(image_id), 'w')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'):difficult = obj.find('difficult').textcls = obj.find('name').textprint(cls)if cls not in classes or int(difficult)==1:continuecls_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')data_path = '/media/COCO/coco_voc_val/images'
img_names = os.listdir(data_path)list_file = open('2014_val.txt', 'w')
for img_name in img_names:if not os.path.exists('coco_voc_val/labels'):os.makedirs('coco_voc_val/labels')list_file.write('/media/COCO/coco_voc_val/images/%s\n'%img_name)image_id = img_name[:-4]convert_annotation(image_id)list_file.close()
这篇关于python提取COCO数据集中特定的类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!