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))


    
        

    

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值