##¥##2019年结束前最后两小时,写出本年度最后一篇博客,不是博主没地方去跨年,实在是Coding乐趣无穷ahhhh ##¥##

COCO数据集是研究实例分割的通用数据集,但是针对道路环境的数据较少,对于自动驾驶和移动机器人的应用并不适配。而提供道路环境的实例分割数据的数据集目前有KITTI、CityScapes、Apllo等,CityScapes算是应用较广,数据质量较高的一个,所以,本篇博文给大家分享一下将CityScapes的实例标注转换为COCO格式的过程。

首先,COCO的标注信息格式参考博文:https://blog.csdn.net/u012609509/article/details/88680841,COCO的图片文件均放在一个文件夹下,而其标注信息都放在annotation文件夹的不同.json文本中,一个文本中包含了对所有图片以及某一任务的所有图片的标注信息。

CityScapes提供的标注信息有彩色语义图、实例id单通道图、语义id单通道图以及所有语义polygon的文本描述.json:

一个COCO标注文件中包含info、lisenses、categories、images以及annotations,代码初始预先设定了前三项,categories可以根据自己的需要进行修改,我保留的类别有5类,car、pedestrian(person)、truck、bus、rider,对应cityscapes中类别id的24-28, 以下是cityscapes完整的类别定义:

List of cityscapes labels:name |  id | trainId |       category | categoryId | hasInstances | ignoreInEval--------------------------------------------------------------------------------------------------unlabeled |   0 |     255 |           void |          0 |            0 |            1ego vehicle |   1 |     255 |           void |          0 |            0 |            1rectification border |   2 |     255 |           void |          0 |            0 |            1out of roi |   3 |     255 |           void |          0 |            0 |            1static |   4 |     255 |           void |          0 |            0 |            1dynamic |   5 |     255 |           void |          0 |            0 |            1ground |   6 |     255 |           void |          0 |            0 |            1road |   7 |       0 |           flat |          1 |            0 |            0sidewalk |   8 |       1 |           flat |          1 |            0 |            0parking |   9 |     255 |           flat |          1 |            0 |            1rail track |  10 |     255 |           flat |          1 |            0 |            1building |  11 |       2 |   construction |          2 |            0 |            0wall |  12 |       3 |   construction |          2 |            0 |            0fence |  13 |       4 |   construction |          2 |            0 |            0guard rail |  14 |     255 |   construction |          2 |            0 |            1bridge |  15 |     255 |   construction |          2 |            0 |            1tunnel |  16 |     255 |   construction |          2 |            0 |            1pole |  17 |       5 |         object |          3 |            0 |            0polegroup |  18 |     255 |         object |          3 |            0 |            1traffic light |  19 |       6 |         object |          3 |            0 |            0traffic sign |  20 |       7 |         object |          3 |            0 |            0vegetation |  21 |       8 |         nature |          4 |            0 |            0terrain |  22 |       9 |         nature |          4 |            0 |            0sky |  23 |      10 |            sky |          5 |            0 |            0person |  24 |      11 |          human |          6 |            1 |            0rider |  25 |      12 |          human |          6 |            1 |            0car |  26 |      13 |        vehicle |          7 |            1 |            0truck |  27 |      14 |        vehicle |          7 |            1 |            0bus |  28 |      15 |        vehicle |          7 |            1 |            0caravan |  29 |     255 |        vehicle |          7 |            1 |            1trailer |  30 |     255 |        vehicle |          7 |            1 |            1train |  31 |      16 |        vehicle |          7 |            1 |            0motorcycle |  32 |      17 |        vehicle |          7 |            1 |            0bicycle |  33 |      18 |        vehicle |          7 |            1 |            0license plate |  -1 |      -1 |        vehicle |          7 |            0 |            1

具体的转换代码如下:

import cv2
import numpy as np
import os, glob
import datetime
import json
import os
import re
import fnmatch
from PIL import Image
import numpy as np
from pycococreatortools import pycococreatortoolsROOT_DIR = '/data/cityscapes/val'
IMAGE_DIR = os.path.join(ROOT_DIR, "images/frankfurt")
ANNOTATION_DIR = os.path.join(ROOT_DIR, "gt/frankfurt")
INSTANCE_DIR = os.path.join(ROOT_DIR, "instances") INFO = {"description": "Cityscapes_Instance Dataset","url": "https://github.com/waspinator/pycococreator","version": "0.1.0","year": "2019","contributor": "Kevin_Jia","date_created": "2019-12-30 16:16:16.123456"
}LICENSES = [{"id": 1,"name": "Attribution-NonCommercial-ShareAlike License","url": "http://creativecommons.org/licenses/by-nc-sa/2.0/"}
]CATEGORIES = [{'id': 1,'name': 'car','supercategory': 'cityscapes',},{'id': 2,'name': 'pedestrian','supercategory': 'cityscapes',},{'id': 3,'name': 'truck','supercategory': 'cityscapes',},{'id': 4,'name': 'bus','supercategory': 'cityscapes',},{'id': 5,'name': 'rider','supercategory': 'cityscapes',}
]background_label = list(range(-1, 24, 1)) + list(range(29, 34, 1))def masks_generator(imges):idx = 0for pic_name in imges:annotation_name = pic_name.split('_')[0] + '_' + pic_name.split('_')[1] + '_' + pic_name.split('_')[2] + '_gtFine_instanceIds.png'print(annotation_name)annotation = cv2.imread(os.path.join(ANNOTATION_DIR, annotation_name), -1)name = pic_name.split('.')[0]h, w = annotation.shape[:2]ids = np.unique(annotation)for id in ids:if id in background_label:continueinstance_id = idclass_id = instance_id // 1000if class_id == 24:instance_class = 'pedestrian'elif class_id == 25:instance_class = 'rider' elif class_id == 26:instance_class = 'car'elif class_id == 27:instance_class = 'truck'elif class_id == 28:instance_class = 'bus'else:continueprint(instance_id)instance_mask = np.zeros((h, w, 3),dtype=np.uint8)mask = annotation == instance_idinstance_mask[mask] = 255mask_name = name + '_' + instance_class + '_' + str(idx) + '.png'cv2.imwrite(os.path.join(INSTANCE_DIR, mask_name), instance_mask)idx += 1def filter_for_pic(files):file_types = ['*.jpeg', '*.jpg', '*.png']file_types = r'|'.join([fnmatch.translate(x) for x in file_types])files = [f for f in files if re.match(file_types, f)]# files = [os.path.join(root, f) for f in files]return filesdef filter_for_instances(root, files, image_filename):file_types = ['*.png']file_types = r'|'.join([fnmatch.translate(x) for x in file_types])files = [f for f in files if re.match(file_types, f)]basename_no_extension = os.path.splitext(os.path.basename(image_filename))[0]file_name_prefix = basename_no_extension + '.*'# files = [os.path.join(root, f) for f in files]files = [f for f in files if re.match(file_name_prefix, os.path.splitext(os.path.basename(f))[0])]return filesdef main():# for root, _, files in os.walk(ANNOTATION_DIR):files = os.listdir(IMAGE_DIR)image_files = filter_for_pic(files)masks_generator(image_files)coco_output = {"info": INFO,"licenses": LICENSES,"categories": CATEGORIES,"images": [],"annotations": []}image_id = 1segmentation_id = 1files = os.listdir(INSTANCE_DIR)instance_files = filter_for_pic(files)# go through each imagefor image_filename in image_files:image_path = os.path.join(IMAGE_DIR, image_filename)image = Image.open(image_path)image_info = pycococreatortools.create_image_info(image_id, os.path.basename(image_filename), image.size)coco_output["images"].append(image_info)# filter for associated png annotations# for root, _, files in os.walk(INSTANCE_DIR):annotation_files = filter_for_instances(INSTANCE_DIR, instance_files, image_filename)# go through each associated annotationfor annotation_filename in annotation_files:annotation_path = os.path.join(INSTANCE_DIR, annotation_filename)print(annotation_path)class_id = [x['id'] for x in CATEGORIES if x['name'] in annotation_filename][0]category_info = {'id': class_id, 'is_crowd': 'crowd' in image_filename}binary_mask = np.asarray(Image.open(annotation_path).convert('1')).astype(np.uint8)annotation_info = pycococreatortools.create_annotation_info(segmentation_id, image_id, category_info, binary_mask,image.size, tolerance=2)if annotation_info is not None:coco_output["annotations"].append(annotation_info)segmentation_id = segmentation_id + 1image_id = image_id + 1with open('{}/frankfurt.json'.format(ROOT_DIR), 'w') as output_json_file:json.dump(coco_output, output_json_file)if __name__ == "__main__":main()

代码的思路是根据cityscapes中的gtFine_instanceids.png获取每个instance的二值Mask图像并保存到INSTANCE_DIR中,文件名格式是:

<原始图片文件名>_<类别名>_<实例序号>.png

随后,读入图片,并依次找出所有对应该图片的Mask,利用coco的API实现images和annotations的生成,并保存。

使用时,需要修改最开始的ROOT_DIR, IMAGES_DIR, ANNOTATION_DIR,并且在ROOT_DIR下创建存放实例Mask的INSTANCE_DIR。

此外,生成.json之后,最好查看以下标注的转换是否正确,博主也写了脚本,很短,大家稍加阅读就可以使用。

原始的COCO API中只能够像下图一样显示instance的polygon区域,没有bounding box以及class,不便于查看。

为此,在coco.showAnns基础上稍作了修改,加入绘制bbox以及左上角写类别,效果如下:

上述代码均已上传在Github:https://github.com/KevinJia1212/cityscapes2coco,如有疑问欢迎大家留言。

###############################################更新分割线####################################

应各位要求,我已将转换好的数据集上传至baidu网盘:

链接:https://pan.baidu.com/s/1bjDp9YsmXDx-TJk4R1jzhw 
提取码:au9b

注意:此数据集仅包含car、pedestrian(person)、truck、bus、rider五类标签,如需其他类别请自行利用转换代码转换。

将CityScapes数据集转换为COCO格式的实例分割数据集相关推荐

  1. 化学实验室自动化 - 1. 深度学习视觉检测(实例分割) - COCO格式的化学实验室常见物体实例分割数据集制作

    前言 随着自动化.智能化技术在各行各业获得了广泛应用,化学实验室领域也不可避免的迎来了变革.视觉检测是自动化和智能化的基础,本文将介绍化学实验室常见物体的COCO格式的实例分割数据集的制作方法,后续将 ...

  2. 将数据集转换为Excel格式的一个实现

    { 将数据集转换为Excel格式的一个实现 在做项目时,很多情况下,客户需要对我们保存在数据库中的数据再加工再利用, 如财务需要一份今年财务情况的电子报表,总经理需要今年销售情况的一个电子报表. 我们 ...

  3. 使用PaddleDetection自带脚本将自制labelme数据集转为coco格式

    问题 PaddleDetection(ppdet)自带一个能将labelme标注的数据集转为coco格式的脚本,还能设置比例分配train.val和test数据集的比例.当前使用的ppdet版本为ve ...

  4. Embrapa酿酒葡萄实例分割数据集-Embrapa WGISD

    Embrapa酿酒葡萄实例分割数据集-Embrapa WGISD 数据集 目的 描述 组成 链接 数据集 点击下载数据集 目的 研究基于图像监控和葡萄栽培现场机器人的目标检测和实例分割.它提供了五个不 ...

  5. ResNeSt 登顶COCO数据集(目标检测,实例分割,全景分割)

    点击上方"视学算法",选择加"星标"或"置顶" 重磅干货,第一时间送达 编辑:Cver 本文作者:张航 https://zhuanlan.z ...

  6. Facebook 开源高质量实例分割数据集 LVIS

    acebook 近日开源了一个具有高质量实例分割的数据集,LVIS.v0.5 包含了用于训练以及验证的 82k 图像中的 1230 个对象类别,注释有超过 700k 的分割掩码.即将到来的 ICCV ...

  7. 视频语义显著实例分割数据集SESIV

    视频区域中,显著区域中有语义意义的组建,即语义显著实例.为解决视频语义显著实例分割,来自日本SOKENDAI和National Institute of Informatics的学者构建了一个新的数据 ...

  8. IndexError: list index out of range coco数据集转换为voc格式出现的错误

    问题: 出现这个问题的地方: 解决办法: 成功!

  9. python读取CIFAR10数据集并将数据集转换为PNG格式存储

    CIFAR10数据集介绍 CIFAR10数据集包括10类图像,每张图像的大小为32*32,包含如上图的十个类别的对象.每个类都包含6000张图片,总共有60000张图片,数据集平衡.其中,训练组图像包 ...

最新文章

  1. RSA加密传输代码示例
  2. 编码练习——Java-5-接口、继承与多态
  3. 使Element默认字体为中文
  4. Java 11都有哪些新特性?
  5. tomcat高版本之URL解析异常解决
  6. java 上传文件及预览_SpringBoot上传下载文件及在线预览
  7. htmlunit爬取js异步加载后的页面
  8. TiKV 正式从 CNCF 毕业,成为云原生时代构建分布式系统的基石
  9. 编程之美 4.6桶中取黑白球
  10. 4.5 Spark SQL 处理JSON数据
  11. 什么是Word2Vec?如何有效的表征文本的?
  12. 动图体积太大怎么缩小?教你一招快速压缩gif
  13. Redis 保证数据一致性方案解析
  14. OC 5028B欧创芯原装,开关降压型大功率恒流驱动芯片
  15. impress.js css模板,使用impress.js制作幻灯片
  16. 关于Python入门的常用工具Wing你了解多少
  17. 《社会动物——爱、性格和成就的潜在根源》读后感及摘录(3)
  18. 人脸识别服务器型号,人脸识别服务器,人脸识别接口,人脸识别方案定制开发
  19. 基于JSP的某餐厅点餐系统
  20. 我的第二本译作《精通OpenStack》上架啦:书籍介绍和译者序

热门文章

  1. 嵌入式QT程序同时支持触屏和鼠标的解决办法
  2. liunx下如何使用unzip 如何压缩文件
  3. 实测,so easy的数据管理!
  4. 盒格速 M 2022风口项目电商新玩法
  5. CAD安装与经典模式设置
  6. 简历应该怎么写,HR看一篇简历仅需要5秒吗,简历模板大全
  7. Codeforces630C【水题】
  8. shell 文本处理利器awk命令
  9. 服务器上怎么做网页啊,云服务器上怎么做网页
  10. 计蒜客 I小灰灰的笼外领地(计算多边形面积)