json labelme coco

1 json数据写入txt

# coding:utf-8
 
import os
import json
import numpy as np

def json2txt(path_json,path_txt):
    with open(path_json,'r', encoding='gb18030') as path_json:
        jsonx=json.load(path_json)
        strxy = ''
        with open(path_txt,'w+') as ftxt:
            for shape in jsonx['shapes']:
                xy=np.array(shape['points'])
                print(xy)
                label=str(shape['label'])
                print(label)    
                for m,n in xy:
                    strxy+=str(m)+','+str(n)+','
                # strxy+= 'Latin'+','+ label
            ftxt.writelines(strxy+"\n")
 
dir_json = 'json/'
dir_txt = 'txt/'
if not os.path.exists(dir_txt):
    os.makedirs(dir_txt)
list_json = os.listdir(dir_json)
for cnt,json_name in enumerate(list_json):
    print('cnt=%d,name=%s'%(cnt,json_name))
    path_json = dir_json + json_name
    path_txt = dir_txt + json_name.replace('.json','.txt')
    # print(path_json, path_txt)
    json2txt(path_json, path_txt)















# https://blog.csdn.net/moonlightpeng/article/details/121524510

 link

2  labelme标注后多个json文件转标准coco格式

labelme软件标注后是每张图片都有一个.json文件,这与常用标准coco格式不一致,因此需要进行转换,避免忘记特此记录。

一、下载labelme2coco-master,并cd进去后运行 pip install labelme2coco 进行安装

可直接在此处下载安装对应版本labelme2coco软件,也可找到github版本,cd到相应目录后运行下列命令进行安装

pip install labelme2coco

二、找出所有数据中属于图片的(也可找到所有属于.json的,避免重复)

import os
path = r'E:\working\images'
li = os.listdir(path)
a = []
for i in li:
  if i.split('.')[-1]=='.jpg':
    a.append(i)

三、划分训练集和测试集(此处是按照8:2进行划分,也可自行定义划分方式)

import random
ratio = 0.8
offset = int(len(a)*ratio)
random.shuffle(a) #将a中文件名打乱
train = a[:offset]
test = a[offset:]

四、将训练集和测试集数据分开

import shutil
path = r'E:\working\images'
path_train = r'E:\working\coco\train'
path_test = r'E:\working\coco\test'
for i in train:
  shutil.copy(os.path.join(path,i), os.path.join(path_train, i)) #图片
  shutil.copy(os.path.join(path,i.split('.')[0]+'.json'), os.path.join(path_train, i.split('.')[0]+'.json')) #标注
for i in test:
  shutil.copy(os.path.join(path,i), os.path.join(path_test, i)) #图片
  shutil.copy(os.path.join(path,i.split('.')[0]+'.json'), os.path.join(path_test, i.split('.')[0]+'.json')) #标注

五、json文件合并

import labelme2coco
# 训练集
labelme_folder = r'E:\working\coco\train'
save_json_path = r'E:\working\coco\train\train_coco.json'
labelme2coco.convert(labelme_folder, save_json_path)
# 测试集
labelme_folder = r'E:\working\coco\test'
save_json_path = r'E:\working\coco\test\test_coco.json'
labelme2coco.convert(labelme_folder, save_json_path)

自此便完成了全部数据转换,包括train和test两个文件夹分别存放训练和测试用的图片,还生成了train_coco.json、test_coco.json两个文件,包括所有的训练和测试标签及类别信息。

将labelme格式数据转化为标准的coco数据集格式方式 

猜你喜欢

转载自blog.csdn.net/qq_35054151/article/details/125247442
今日推荐