labelme格式数据的大json转为小json方法

python实现coco数据中图片resize后,通过大图的json得到resize后的json。

labelme格式数据的大json转为小json思想主要是读取大图的宽高,以及resize后的宽高,获得resize前后的宽高比,获取类别,对类别中的points(点)进行逐点按宽高比进行缩放,复制一份大图的json,将获取的点逐个类别替换、图片信息替换。

代码如下

import json
import os
import base64
import cv2
from base64 import b64encode
def resizeSeg(path):
    Width = 0
    Height = 0
     with open(path, "r", encoding='gb2312') as f:
        desc = json.load(f)
        desc_ = desc.copy()
     for key, value in desc.items():
        if key =='imageWidth':
             Width = value
        if key == 'imageHeight':
             Height = value
    for key, value in desc.items():
         if key == 'shapes':
           for ind, cla in enumerate(value):
                for ind2, dian in enumerate(value[ind]["points"]):
                    x = desc['shapes'][ind]["points"][ind2][0]
                    y = desc['shapes'][ind]["points"][ind2][1]
                    x = int((512/Width)*x)
                    y = int((512/Height) * y)
                    desc_['shapes'][ind]["points"][ind2][0] = x
                    desc_['shapes'][ind]["points"][ind2][1] = y
    desc_['imageWidth'] = 512 #小json的w
    desc_['imageHeight'] = 512 #小json的h
    desc_['imagePath'] = path.split('/')[-1]
    png_name = path.replace('.json', '.jpg')
    png_dst = os.path.join("/home/work/mjt/xuanzhuan_train/resizeSeg", os.path.basename(png_name)) #图片路径
    json_dst = os.path.join("/home/work/mjt/xuanzhuan_train/new", os.path.basename(png_name).replace(".jpg", ".json"))#json路径,注意图片格式(.jpg或.png)
    # 读取二进制图片,获得原始字节码
    with open(png_name, 'rb') as jpg_file:
        byte_content = jpg_file.read()
    # 把原始字节码编码成base64字节码
    base64_bytes = b64encode(byte_content)
    # 把base64字节码解码成utf-8格式的字符串
    base64_string = base64_bytes.decode('utf-8')
    with open(png_dst, "rb") as h:
        desc_['imageData'] = base64_string
    # 输出json文件 (也就是与图片相对应的自动标注文件)
    with open(json_dst, "w") as h:
        json.dump(desc_, h,  indent=2)
if __name__ == '__main__':
    path = "/home/work/mjt/xuanzhuan_train/resizeSeg" #json文件夹
    files = os.listdir(path)
    for jsonfile in files:
        if jsonfile.endswith('.json'):
            resizeSeg(os.path.join(path, jsonfile))


    
        

    

你可能感兴趣的:(json,python,视觉检测,目标检测,神经网络)