批量把labelme生成的json文件转换成png图片(本人亲测成功!)

在做一些异常检测模型任务时,需要批量把labelme生成的json文件转换成png图片,在这里把代码共享出来,大家可以需要时就可以拿来用哦!

代码如下:

import base64
import json
import os
import os.path as osp

import numpy as np
import PIL.Image
from labelme import utils

if __name__ == '__main__':
    jpgs_path   = "d:/XYF-code/work/GeneralAD-master/data/mydata/screen/test/NG" #图片所在路径
    pngs_path   = "d:/XYF-code/work/GeneralAD-master/data/mydata/screen/ground_truth/NG"#输出的结果保存路径
    classes     = ["_background_", "NG"]
    
    count = os.listdir("d:/XYF-code/work/GeneralAD-master/data/mydata/screen/ground_truth/1") #(原图+labelme标注生成的.json文件)的路径
    for i in range(len(count)):
        path = os.path.join("d:/XYF-code/work/GeneralAD-master/data/mydata/screen/ground_truth/1", count[i])

        if os.path.isfile(path) and path.endswith('json'):
            data = json.load(open(path))
            
            if data['imageData']:
                imageData = data['imageData']
            else:
                imagePath = os.path.join(os.path.dirname(path), data['imagePath'])
                with open(imagePath, 'rb') as f:
                    imageData = f.read()
                    imageData = base64.b64encode(imageData).decode('utf-8')

            img = utils.img_b64_to_arr(imageData)
            label_name_to_value = {'_background_': 0}
            for shape in data['shapes']:
                label_name = shape['label']
                if label_name in label_name_to_value:
                    label_value = label_name_to_value[label_name]
                else:
                    label_value = len(label_name_to_value)
                    label_name_to_value[label_name] = label_value
            
            # label_values must be dense
            label_values, label_names = [], []
            for ln, lv in sorted(label_name_to_value.items(), key=lambda x: x[1]):
                label_values.append(lv)
                label_names.append(ln)
            assert label_values == list(range(len(label_values)))

            lbl = utils.shapes_to_label(img.shape, data['shapes'], label_name_to_value)
            lbl = lbl[0]  # Assume lbl is a 2D array after shapes_to_label
            
            PIL.Image.fromarray(img).save(osp.join(jpgs_path, count[i].split(".")[0] + '.jpg'))

            # Create new array where the foreground will be white
            new = np.zeros([lbl.shape[0], lbl.shape[1]], dtype=np.uint8)

            for name in label_names:
                index_json = label_names.index(name)
                index_all = classes.index(name)
                if index_all > 0:  # Skip the background
                    new[lbl == index_json] = 255

            # Save the PNG file using PIL.Image
            new_image = PIL.Image.fromarray(new)
            new_image.save(osp.join(pngs_path, count[i].split(".")[0] + '.png'))
            print('Saved ' + count[i].split(".")[0] + '.jpg and ' + count[i].split(".")[0] + '.png')

结果展示:

要是对大家有帮助,我就很开心!!!!!

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值