coco 数据集_Detection学习之二-pascal_voc和coco数据读取

pascal_voc和coco数据集是深度学习中最常用的两个数据集,提供了包括检测、分割、人体关键点等多个不同任务的标注数据。然而,两个数据集在存储架构和标注数据存储上存在比较大的差异,下面分别对两个数据集文件夹结构及标注数据的读取进行简单介绍。

pascal_voc

1、数据集存储架构

pascal_voc数据集分为2007年和2012年两个版本,07版中的图像数据为12版子集,两个版本的数据集在指标计算方面也略有不同(见上一篇Detection学习之一-评价指标mAP的计算)。不失一般性,本文以07版数据集为例进行讲解,12版数据集与此类似。

下载后得到一个名为VOCdevkit的文件,进入到名为VOC2007的子文件夹中,即进入到pascal_voc 2007数据集中。该文件夹又包含Annotations、ImageSets、JPEGImages、SegmentationClass、SegmentationObject几个子文件夹,包含了图像数据、标注数据及训练数据集和验证数据集的划分等信息。

  • JPEGImages 文件夹

提供的是PASCAL VOC所提供的所有的图片信息,包括训练图片,测试图片,这些图像就是用来进行训练和测试验证的图像数据。

  • Annotations文件夹

存放xml格式的标签文件,每个xml对应JPEGImage中的一张图片

  • ImageSets文件夹

又分为以下几个子文件夹

Action-人的动作

Layout-人体部位

Main-图像物体识别的数据,总共20类

Segmentation-用于分割的数据。

以上每个文件夹包括train.txt、val.txt、trainval.txt、test.txt文件,包括了数据集中训练集、验证集和测试集的划分,需要何证train和val中没有交集。

  • SegmentationObject & SegmentationClass

保存的是物体分割后的数据,在物体识别中没有用到

2、标注数据的读取

filename = os.path.join(self._data_path, 'Annotations', index + '.xml')tree = ET.parse(filename)objs = tree.findall('object')# if not self.config['use_diff']:# # Exclude the samples labeled as difficult# non_diff_objs = [# obj for obj in objs if int(obj.find('difficult').text) == 0]# # if len(non_diff_objs) != len(objs):# # print 'Removed {} difficult objects'.format(# # len(objs) - len(non_diff_objs))# objs = non_diff_objsnum_objs = len(objs)boxes = np.zeros((num_objs, 4), dtype=np.uint16)gt_classes = np.zeros((num_objs), dtype=np.int32)overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32)# "Seg" area for pascal is just the box areaseg_areas = np.zeros((num_objs), dtype=np.float32)ishards = np.zeros((num_objs), dtype=np.int32)# Load object bounding boxes into a data frame.for ix, obj in enumerate(objs):bbox = obj.find('bndbox')# Make pixel indexes 0-basedx1 = float(bbox.find('xmin').text) - 1y1 = float(bbox.find('ymin').text) - 1x2 = float(bbox.find('xmax').text) - 1y2 = float(bbox.find('ymax').text) - 1diffc = obj.find('difficult')difficult = 0 if diffc == None else int(diffc.text)ishards[ix] = difficultcls = self._class_to_ind[obj.find('name').text.lower().strip()]boxes[ix, :] = [x1, y1, x2, y2]gt_classes[ix] = clsoverlaps[ix, cls] = 1.0seg_areas[ix] = (x2 - x1 + 1) * (y2 - y1 + 1)overlaps = scipy.sparse.csr_matrix(overlaps)return {'boxes': boxes,'gt_classes': gt_classes,'gt_ishard': ishards,'gt_overlaps': overlaps,'flipped': False,'seg_areas': seg_areas}

以上函数.xml文件中导入index标号对应的图像的标注数据。针对于每一幅图像,对应的是一个dict,具有以下属性:

  • 属性 'boxes',矩阵boxes,大小为图像中物体个数(num_objs)×4,每一行为一个物体的bounding box
  • 属性 'gt_classes',列向量gt_classes,大小为物体个数num_objs,每一个元素为boxes对应行所表示物体的对应index
  • 属性 'gt_overlaps',矩阵overlaps,大小为图像中物体个数(num_objs)×物体类别个数(num_classes),矩阵中物体对应类别元素值为1,其他为0
  • 属性 'flipped',表示当前图像是否是翻转的(True or False),实际读取的物体为false,基类中进行翻转形成的物体为true
  • 属性 'seg_areas',列向量seg_areas,大小为物体个数num_objs,每一个元素为物体所占据面积,即长*宽。

coco

1、数据存储架构

COCO数据集按照年份来区分,有2014、2015和2017版本。根据用途不同,数据集分为目标检测、目标分割(对应标注信息为'bbox'和'segmentation'),图像语义理解('captions')、人体关节点('keypoints')。

下载完COCO2014后进行解压后,目录如下:

  • train2014
  • val2014
  • test2014
  • annotations

其中,images中的文件夹各自放置了训练、验证和测试的数据集图片。annotations文件夹中放置了标签文件。

为了更好的使用数据集,COCO对数据集的标注信息做了统一管理。其中,图像检测数据集的标注数据保存在.json文件中。例如,2017_val的标注数据就保存在instances_val2017.json文件中。如下图所示。

b1b81b52563b3a81cec300e7d9c9e49a.png

可以看到, 标注文件中有 image 和 annotations 域, annotations 中保存的就是标注信息. 根据不同的应用场景, 标注信息又可分为: 目标的边界框 bbox 和图像分割区域 segmentation.

2、标注数据的读取

介绍如何用 COCO 提供的 Python API 来提取这些信息.

1) 加载json文件,并解析其中的标注信息

from pycocotools.coco import COCOdataDir='/path/to/your/coco_data'dataType='val2017'annFile='{}/annotations/instances_{}.json'.format(dataDir,dataType)# 初始化标注数据的 COCO api coco=COCO(annFile)

COCO 是一个类, 因此, 使用构造函数创建一个 COCO 对象, 构造函数首先会加载 json 文件, 然后解析图片和标注信息的 id, 根据 id 来创建其关联关系.

COCO 对象创建完毕后会输出如下信息

loading annotations into memory...Done (t=0.81s)creating index...index created!

2) 显示 COCO 数据集中的具体类和超类

# display COCO categories and supercategoriescats = coco.loadCats(coco.getCatIds())nms=[cat['name'] for cat in cats]print('COCO categories: {}'.format(' '.join(nms)))nms = set([cat['supercategory'] for cat in cats])print('COCO supercategories: {}'.format(' '.join(nms)))

输出如下

COCO categories: 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 toothbrushCOCO supercategories: outdoor food indoor appliance sports person animal vehicle furniture accessory electronic kitchen
  • 函数loadCats(self, ids=[]),返回的是从 json 文件加载进来的 80 类对象. 这个函数接收一个 id list 作为参数, 如果没有指定 id 参数, 那么函数返回也为一个空 list. 本例中使用 getCatIds(self, catNms=[], supNms=[], catIds=[]) 函数获取 id 作为参数。
  • 函数getCatIds(self, catNms=[], supNms=[], catIds=[]) 如果不指定参数, 则返回所有类的 id, 否则, 返回指定类的 id ( 类可以通过 'name', 'supercategory' 或 'id' 指定)

3) 加载并显示指定 id 的图片

# get all images containing given categories, select one at randomcatIds = coco.getCatIds(catNms=['person','dog','skateboard']);imgIds = coco.getImgIds(catIds=catIds );imgIds = coco.getImgIds(imgIds = [324158])// loadImgs() 返回的是只有一个元素的列表, 使用[0]来访问这个元素// 列表中的这个元素又是字典类型, 关键字有: ["license
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值