reference
提供了转换代码,需要改写部分
https://github.com/fengzhongyouxia/TensorExpand/tree/master/TensorExpand/Object detection/Data_interface/MSCOCO/labelme data

注:命名时候尽量按照要求,按照"父_子类_num"样式去命名,否则会报错list 越界(吃了大亏,改程序手改标定。。。)
同时发现,似乎不加area 参数,只用image\annotation\category就能进行训练(所以在labelme2coco.py中,就是只转换了这三个)
coco.json说明
https://blog.csdn.net/yeyang911/article/details/78675942
https://blog.csdn.net/wc781708249/article/details/79603522#可视化
这里写一个class实现以下功能,labelme2COCO.py中 的部分代码如下:

# -*- coding:utf-8 -*-
# !/usr/bin/env pythonimport argparse
import json
import matplotlib.pyplot as plt
import skimage.io as io
import cv2
from labelme import utils
import numpy as np
import glob
import PIL.Imageclass labelme2coco(object):def __init__(self,labelme_json=[],save_json_path='./new.json'):''':param labelme_json: 所有labelme的json文件路径组成的列表:param save_json_path: json保存位置'''self.labelme_json=labelme_jsonself.save_json_path=save_json_pathself.images=[]self.categories=[]self.annotations=[]# self.data_coco = {}self.label=[]self.annID=1self.height=0self.width=0self.save_json()def data_transfer(self):for num,json_file in enumerate(self.labelme_json):with open(json_file,'r') as fp:data = json.load(fp)  # 加载json文件self.images.append(self.image(data,num))for shapes in data['shapes']:label=shapes['label'].split('_')if label[1] not in self.label:self.categories.append(self.categorie(label))self.label.append(label[1])points=shapes['points']self.annotations.append(self.annotation(points,label,num))self.annID+=1def image(self,data,num):image={}img = utils.img_b64_to_array(data['imageData'])  # 解析原图片数据# img=io.imread(data['imagePath']) # 通过图片路径打开图片# img = cv2.imread(data['imagePath'], 0)height, width = img.shape[:2]img = Noneimage['height']=heightimage['width'] = widthimage['id']=num+1image['file_name'] = data['imagePath'].split('/')[-1]self.height=heightself.width=widthreturn imagedef categorie(self,label):categorie={}categorie['supercategory'] = label[1]categorie['id']=len(self.label)+1 # 0 默认为背景categorie['name'] = label[1]return categoriedef annotation(self,points,label,num):annotation={}annotation['segmentation']=[list(np.asarray(points).flatten())]annotation['iscrowd'] = 0annotation['image_id'] = num+1# annotation['bbox'] = str(self.getbbox(points)) # 使用list保存json文件时报错(不知道为什么)# list(map(int,a[1:-1].split(','))) a=annotation['bbox'] 使用该方式转成listannotation['bbox'] = list(map(float,self.getbbox(points)))annotation['category_id'] = self.getcatid(label)annotation['id'] = self.annIDreturn annotationdef getcatid(self,label):for categorie in self.categories:if label[0]==categorie['name']:return categorie['id']return -1def getbbox(self,points):# img = np.zeros([self.height,self.width],np.uint8)# cv2.polylines(img, [np.asarray(points)], True, 1, lineType=cv2.LINE_AA)  # 画边界线# cv2.fillPoly(img, [np.asarray(points)], 1)  # 画多边形 内部像素值为1polygons = pointsmask = self.polygons_to_mask([self.height,self.width], polygons)return self.mask2box(mask)def mask2box(self, mask):'''从mask反算出其边框mask:[h,w]  0、1组成的图片1对应对象,只需计算1对应的行列号(左上角行列号,右下角行列号,就可以算出其边框)'''# np.where(mask==1)index = np.argwhere(mask == 1)rows = index[:, 0]clos = index[:, 1]# 解析左上角行列号left_top_r = np.min(rows)  # yleft_top_c = np.min(clos)  # x# 解析右下角行列号right_bottom_r = np.max(rows)right_bottom_c = np.max(clos)# return [(left_top_r,left_top_c),(right_bottom_r,right_bottom_c)]# return [(left_top_c, left_top_r), (right_bottom_c, right_bottom_r)]# return [left_top_c, left_top_r, right_bottom_c, right_bottom_r]  # [x1,y1,x2,y2]return [left_top_c, left_top_r, right_bottom_c-left_top_c, right_bottom_r-left_top_r]  # [x1,y1,w,h] 对应COCO的bbox格式def polygons_to_mask(self,img_shape, polygons):mask = np.zeros(img_shape, dtype=np.uint8)mask = PIL.Image.fromarray(mask)xy = list(map(tuple, polygons))PIL.ImageDraw.Draw(mask).polygon(xy=xy, outline=1, fill=1)mask = np.array(mask, dtype=bool)return maskdef data2coco(self):data_coco={}data_coco['images']=self.imagesdata_coco['categories']=self.categoriesdata_coco['annotations']=self.annotationsreturn data_cocodef save_json(self):self.data_transfer()self.data_coco = self.data2coco()# 保存json文件json.dump(self.data_coco, open(self.save_json_path, 'w'), indent=4)  # indent=4 更加美观显示#labelme_json=glob.glob('./test_img/*.json')
labelme_json=glob.glob('./bird.json')
# labelme_json=['./1.json']labelme2coco(labelme_json,'./new.json')

一个更改生成:

# -*- coding:utf-8 -*-import json
import cv2
import numpy as nplabelme_json='./bird.json'
data=json.load(open(labelme_json))data_coco={}# images
images=[]
image={}
file_name=data['imagePath'].split('\\')[-1] # windows \\ ;linux /
image['file_name']=file_name
image['id']=0 # 每张图片对应的id都是唯一的# img=cv2.imread(data['imagePath'])
img=cv2.imread('./eagle.jpg')
image['height']=img.shape[0]
image['width']=img.shape[1]
img=Noneimages.append(image)data_coco['images']=images# categories
categories=[]categorie={}
categorie['supercategory']='bird'
categorie['id']=1 # id 唯一 0 默认为背景
categorie['name']='eagle' # 波斯猫
categories.append(categorie)
'''
categorie={}
categorie['supercategory']='cat'
categorie['id']=2
categorie['name']='garden Cat' # 田园猫
categories.append(categorie)
'''
data_coco['categories']=categories# annotations
annotations=[]
annotation={}annotation['segmentation']=[list(np.asarray(data['shapes'][0]['points']).flatten())]   # data['shapes'][0]['points']
annotation['iscrowd']=0
annotation['image_id']=image['id']
annotation['bbox']=[] # 先空着,需要反算出定位框
annotation['category_id']=1
annotation['id']=1 # 第一个对象 这个ID也不能重复,如果下一张图,id不能取1,需从1 开始往下取
annotations.append(annotation)
'''
annotation={}
annotation['segmentation']=[list(np.asarray(data['shapes'][1]['points']).flatten())]
annotation['iscrowd']=0
annotation['image_id']=image['id']
annotation['bbox']=[] # 先空着,需要反算出定位框
annotation['category_id']=2
annotation['id']=2 # 第一个对象 这个ID也不能重复,如果下一张图,id不能取1,需从1 开始往下取
annotations.append(annotation)
'''
data_coco['annotations']=annotations# 保存json文件
json.dump(data_coco,open('./new_instances_bird.json','w'),indent=4) # indent=4 更加美观显示

增加area
from shapely.geometry import Polygon
area_ = round(poly.area,6)
annotation[‘area’] = area_

# -*- coding:utf-8 -*-
# !/usr/bin/env pythonimport argparse
import json
import matplotlib.pyplot as plt
import skimage.io as io
import cv2
from labelme import utils
import numpy as np
import glob
import PIL.Image
from shapely.geometry import Polygon#https://shapely.readthedocs.io/en/latest/manual.html#geometric-objectsclass labelme2coco(object):def __init__(self,labelme_json=[],save_json_path='D:/haidee/new/'):''':param labelme_json: 所有labelme的json文件路径组成的列表:param save_json_path: json保存位置'''self.labelme_json=labelme_json#所有的json文件self.save_json_path=save_json_path#输出文件new.json的路径self.images=[]self.categories=[]self.annotations=[]# self.data_coco = {}self.label=[]self.annID=1self.height=0self.width=0self.save_json()#我的数据用label标注的名称格式是:car_car_1,car_car_2,...修改label的截断以符合自己的数据,或者按照我的命名def data_transfer(self):for num,json_file in enumerate(self.labelme_json):with open(json_file,'r') as fp:data = json.load(fp)  # 加载json文件self.images.append(self.image(data,num))for shapes in data['shapes']:label=shapes['label'].split('_')if label[1] not in self.label:self.categories.append(self.categorie(label))self.label.append(label[1])points=shapes['points']self.annotations.append(self.annotation(points,label,num))self.annID+=1def image(self,data,num):image={}img = utils.img_b64_to_arr(data['imageData'])  # 解析原图片数据# img=io.imread(data['imagePath']) # 通过图片路径打开图片# img = cv2.imread(data['imagePath'], 0)height, width = img.shape[:2]img = Noneimage['height']=heightimage['width'] = widthimage['id']=num+1image['file_name'] = data['imagePath'].split('/')[-1]self.height=heightself.width=widthreturn imagedef categorie(self,label):categorie={}categorie['supercategory'] = label[1]categorie['id']=len(self.label)+1 # 0 默认为背景categorie['name'] = label[1]return categoriedef annotation(self,points,label,num):annotation={}annotation['segmentation']=[list(np.asarray(points).flatten())]poly = Polygon(points)annotation['iscrowd'] = 0annotation['image_id'] = num+1area_ = round(poly.area,6)annotation['area'] = area_# annotation['bbox'] = str(self.getbbox(points)) # 使用list保存json文件时报错(不知道为什么)# list(map(int,a[1:-1].split(','))) a=annotation['bbox'] 使用该方式转成listannotation['bbox'] = list(map(float,self.getbbox(points)))annotation['category_id'] = self.getcatid(label)annotation['id'] = self.annIDreturn annotationdef getcatid(self,label):for categorie in self.categories:if label==categorie['name']:return categorie['id']return -1def getbbox(self,points):# img = np.zeros([self.height,self.width],np.uint8)# cv2.polylines(img, [np.asarray(points)], True, 1, lineType=cv2.LINE_AA)  # 画边界线# cv2.fillPoly(img, [np.asarray(points)], 1)  # 画多边形 内部像素值为1polygons = pointsmask = self.polygons_to_mask([self.height,self.width], polygons)return self.mask2box(mask)def mask2box(self, mask):'''从mask反算出其边框mask:[h,w]  0、1组成的图片1对应对象,只需计算1对应的行列号(左上角行列号,右下角行列号,就可以算出其边框)'''# np.where(mask==1)index = np.argwhere(mask == 1)rows = index[:, 0]clos = index[:, 1]# 解析左上角行列号left_top_r = np.min(rows)  # yleft_top_c = np.min(clos)  # x# 解析右下角行列号right_bottom_r = np.max(rows)right_bottom_c = np.max(clos)return [left_top_c, left_top_r, right_bottom_c-left_top_c, right_bottom_r-left_top_r]  # [x1,y1,w,h] 对应COCO的bbox格式def polygons_to_mask(self,img_shape, polygons):mask = np.zeros(img_shape, dtype=np.uint8)mask = PIL.Image.fromarray(mask)xy = list(map(tuple, polygons))PIL.ImageDraw.Draw(mask).polygon(xy=xy, outline=1, fill=1)mask = np.array(mask, dtype=bool)return maskdef data2coco(self):data_coco={}data_coco['images']=self.imagesdata_coco['categories']=self.categoriesdata_coco['annotations']=self.annotationsreturn data_cocodef save_json(self):self.data_transfer()self.data_coco = self.data2coco()# 保存json文件json.dump(self.data_coco, open(self.save_json_path, 'w'), indent=4)  # indent=4 更加美观显示labelme_json=[]
for i in range(0,92):#遍历所有的labelme 标准的json,载入并转换#ind='./test_img/val_img/s{index}.json'.format(index=i)ind='E:/Data_Set/mask-cai/four_cls/s{index}.json'.format(index=i)labelme_json.append(ind)lab = labelme2coco(labelme_json,'./sileiv2_with_area.json')#调用labelme2coco类
print('Saved to :',lab.save_json_path)#保存

labelme json转换为coco json 格式 包含area面积相关推荐

  1. Java XML转换为JSON XML解析 转换为JSON Java 实现JSON转换为XML json转xml

    Java XML转换为JSON XML解析 转换为JSON Java 实现JSON转换为XML json转xml 一.转换代码 1.XML字符串转换为JSON /*** description: XM ...

  2. labelme标注文件转coco json,coco json转yolo txt格式,coco json转xml, labelme标注文件转分割,boxes转labelme json

    参考:https://github.com/wkentaro/labelme 一.labelme标注文件转coco json 1.标注时带图片ImageData信息,将一个文件夹下的照片和labelm ...

  3. voc数据集格式转换为coco数据集格式+修改xml格式文件

    voc数据集格式转换为coco格式+修改xml格式文件中部分内容 voc数据集格式→coco数据集格式 修改xml格式文件中部分内容 voc数据集格式→coco数据集格式 下面这份代码只需修改文件所在 ...

  4. COCO 数据集格式及mmdetection中的转换方法

    COCO 数据集格式及mmdetection中的转换方法 COCO格式 CV中的目标检测任务不同于分类,其标签的形式稍为复杂,有几种常用检测数据集格式,本文将简要介绍最为常见的COCO数据集的格式. ...

  5. LabelMe标记后的json文件怎么转为COCO格式

    LabelMe标记后的json文件怎么转为COCO格式 步骤如下: Step 1: 下载labelme ,链接为https://github.com/wkentaro/labelme Step 2: ...

  6. voc定位数据xml转coco数据集格式json

    代码里面集合了python处理xml的精髓 import xml.etree.ElementTree as ET import os import jsoncoco = dict() coco['im ...

  7. 用labelme标注矩形框和关键点得到的json文件转txt格式用于yolov5-face训练

    目录 我用labelme标注完的json文件长这样:标注了两种:矩形框和点 我要转换的txt格式长这样: json格式转txt如下: 从txt查看标注结果 参考的这位博主并在此基础上做了改动.(484 ...

  8. 安卓取map集合转换为json_android json解析成map格式

    "discount": { "3": "34", "4": "33", "5": ...

  9. 读取TXT文本内容,并转换为Json字符串(固定格式)

    这周因为工作需要,接手到一个手写工具类的任务.具体要求就是,将公司的1000条货单数据,以100条为一组的形式,每一组都转换为一个json字符串.用来发布给中间件做接口测试使用.具体数据有1000条, ...

最新文章

  1. Yii 错误页面处理
  2. python美国股票数据api_【美股量化00篇】Python获取新浪接口美股实时数据
  3. spire.doc 转html,c# html 转Word--Spire.Doc
  4. DotNet语音技术实现(实现电脑发音)
  5. 15.赋值运算符为什么返回类的引用?不是引用怎么办?
  6. Flask之flask-session
  7. Linux发邮件之mail命令
  8. 95-290-360-源码-内存管理-Buffer-ByteBufferPool简介
  9. java对接电信nb物联网平台_解决传统GPS定位弊端,中国电信NB网关一招致胜
  10. 命令模式(3)-宏命令
  11. linux sendemail,在linux下使用sendEmail发送邮件
  12. Sound Grinder Pro for Mac(音频批量编辑转换工具)
  13. html5的优点与缺点大概总结
  14. 小米6线刷包php文件格式,小米6线刷教程 小米6线刷包_救砖包下载
  15. 电子罗盘在终端的应用
  16. android+锁屏显示农历,在手机锁屏界面上显示农历日期和天气
  17. 手机重装android系统,安卓手机系统怎样重装
  18. Matlab纵向比和横向比,宽度是横向还是纵向-纵向比和横向比-纵向是横向还是竖向...
  19. 中国的RFID产业何时才能统一标准
  20. Oracle用户被锁定问题

热门文章

  1. FFmpeg滤镜:制作图片视频流(续2)
  2. C语言自定义输入10000个整数,C语言
  3. 转:成为Java高级程序员需要掌握哪些?
  4. 龙芯3A5000搭建idea开发环境
  5. Apache2.4的安装、配置与常见的问题(Windows)
  6. windows系统nginx重启发生异常
  7. CentOS 7 源码编译安装 Nginx
  8. 如何根据笔记本CPU选取合适内存条总结
  9. 磁链Ψ、磁通φ、磁势F
  10. 红点奖设计概念奖设计之星奖