由于自己的处理数据需求和labelme的直接使用处理还有差距,所以特此开发了新的工具,鸣谢我的合作伙伴,由于labelme工具解析json开源,则采用使得数据组织格式和标准json相同的方式。
解析代码如下:
修改文件为:D:\Users\Pangzhennan\Anaconda3\envs\labelme\Lib\site-packages\labelme\cli\json_to_dataset.py
此处路径同批量操作文件的代码。
# -*- coding: utf-8 -*-
import argparse
import json
import os
import os.path as osp
import warnings
import PIL.Image
import yaml
from labelme import utils
import base64
def main():
warnings.warn("This script is aimed to demonstrate how to convert the\n"
"JSON file to a single image dataset, and not to handle\n"
"multiple JSON files to generate a real-use dataset.")
parser = argparse.ArgumentParser()
parser.add_argument('json_file')
parser.add_argument('-o', '--out', default=None)
args = parser.parse_args()
json_file = args.json_file
# 该段代码在此处无意义
'''
if args.out is None:
out_dir = osp.basename(json_file).replace('.', '_')
out_dir = osp.join(osp.dirname(json_file), out_dir)
else:
out_dir = args.out
if not osp.exists(out_dir):
os.mkdir(out_dir)
'''
list = os.listdir(json_file)
for i in range(0, len(list)):
path = os.path.join(json_file, list[i])
'''
print('path===================')
print(path)
kkk = open(path)
print(kkk)
print(type(kkk))
'''
if os.path.isfile(path):
#with open(path,'r') as load_f: #pang_add method1;
#data = json.load(load_f)
#data = json.load(open(path)) #pang_add method2;
data = json.load(open(path, 'r')) #pang_add method2;
'''
print('data===================')
print(data)
print(type(data))
'''
img = utils.img_b64_to_array(data['imageData'])
lbl, lbl_names = utils.labelme_shapes_to_label(img.shape, data['shapes'])
captions = ['%d: %s' % (l, name) for l, name in enumerate(lbl_names)]
lbl_viz = utils.draw_label(lbl, img, captions)
out_dir = osp.basename(list[i]).replace('.', '_')
out_dir = osp.join(osp.dirname(list[i]), out_dir)
if not osp.exists(out_dir):
os.mkdir(out_dir)
PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
PIL.Image.fromarray(lbl).save(osp.join(out_dir, 'label.png'))
PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, 'label_viz.png'))
with open(osp.join(out_dir, 'label_names.txt'), 'w') as f:
for lbl_name in lbl_names:
f.write(lbl_name + '\n')
warnings.warn('info.yaml is being replaced by label_names.txt')
info = dict(label_names=lbl_names)
with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
yaml.safe_dump(info, f, default_flow_style=False)
print('Saved to: %s' % out_dir)
if __name__ == '__main__':
main()
遇到的问题:
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
为了解决该问题,一度认为是自己的json中的字典和内容的格式出现了问题,经排查之后,发现自己的工具保存的json格式为utf-8格式编码,而正常应该是ansi或者cp936(gbk)格式编码。
解决方案为:1.改变工具对于json的编码格式;2.将utf-8编码格式的json文件转化为ansi或者cp936编码格式的文件。
关于utf-8格式和cp936格式的关系:
UTF-8(8-bit Unicode Transformation Format)是一种针对Unicode的可变长字符编码,又称万国码。
GBK全称《汉字内码扩展规范》(Chinese Internal Code Specification),cp936等同于GBK。
ANSI是一种字符代码,为使计算机支持更多语言,通常使用 0x00~0x7f 范围的1 个字节来表示 1 个英文字符。超出此范围的使用0x80~0xFFFF来编码,即扩展的ASCII编码。