分割软件labelme批量把json转成png

本文讲述了如何通过Python脚本将LabelMe生成的医学图像标注从JSON转换为PNG格式,便于模型训练。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在做医学图像分割的相关工作,用到了labelme这一软件,但标注以后直接生成的只有json格式,而跑模型需要png格式的mask,这就需要我们手动做一下转换。

首先我们新建一个.py的文件,我这里的名称为json2png.py,内容如下:

import json
import os
import os.path as osp
 
import warnings
import cv2
 
from labelme import utils
 
import numpy as np
import PIL.Image
import PIL.ImageDraw
 
def json2png(json_file, out_file):
    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.")
 
    # freedom
    list_path = os.listdir(json_file)
    print('freedom =', json_file)
    for i in range(0, len(list_path)):
        print(i)
        path = os.path.join(json_file, list_path[i])
        if os.path.isfile(path):
 
            data = json.load(open(path,encoding="utf-8",errors="ignore"))
            img = utils.img_b64_to_arr(data['imageData'])
            lbl, lbl_names = utils.labelme_shapes_to_label(img.shape, data['shapes'])
 
            mask = []
            mask.append((lbl).astype(np.uint8)) 
            mask = np.asarray(mask,np.uint8)
            mask = np.transpose(np.asarray(mask,np.uint8),[1,2,0])
            retval, im_at_fixed = cv2.threshold(mask[:,:,0], 0, 255, cv2.THRESH_BINARY)
            
            # out_dir = osp.basename(path).replace('.', '_')
            out_dir = osp.basename(path).split('.json')[0]
            save_file_name = out_dir
            # out_dir = osp.join(osp.dirname(path), out_dir)
 
            if not osp.exists(out_file + 'GT'):
                os.mkdir(out_file + 'GT')
            maskdir = out_file + 'GT'
 
            out_dir1 = out_file + 'Image'
            if not osp.exists(out_dir1):
                os.mkdir(out_dir1)
 
            PIL.Image.fromarray(img).save(out_dir1 + '/' + save_file_name + '.jpg')
            PIL.Image.fromarray(im_at_fixed).save(maskdir + '/' + save_file_name + '.png')
 
            print('Saved to: %s' % out_dir1)
 
 
# 图片重命名
def rename(path):
    # path = path + 'Image'
    path = path + 'GT'
    for file in os.listdir(path):
        name = file.split('.')[0]
        name = name.split('_')[1]
        name = name[5:]     # "image1"
        # ‘%04d’表示一共4位数,GT是png,Image是jpg
        os.rename(os.path.join(path, file), os.path.join(path, 'image' + '%04d' % int(name) + ".png"))   
 
if __name__ == '__main__':
    json_file = "D:/deep-learning/jidimo/糖尿病肾病-电镜/wo/json/" # 文件夹里面全是json
    out_file = "D:/deep-learning/jidimo/糖尿病肾病-电镜/wo/label/"
    json2png(json_file, out_file)
    # rename(out_file)

需要注意的是,在最后的代码中要改一下文件夹的路径。

接着打开anaconda prompt命令行,切换环境到labelme:

切换路径到新建python文件的目录下:

需要在保存png的文件夹下新建GT文件夹:

然后在终端输入代码:

python json2png.py json文件夹路径

截图如下:

虽然有警告,但已经成功完成了转换!转换好的图片就保存在上面新建的GT文件夹里面:

如果对你有帮助的话,可以点赞收藏一下哦~

### 将LabelMe JSON文件换为适合训练的数据集标签格式 #### 换流程概述 为了使由LabelMe生成的JSON文件适用于机器学习模型训练,需将其换成特定框架所支持的标准格式。此过程涉及解析原始JSON文件结构,并依据目标数据集标准重新组织标注信息。 #### 解析与准备 LabelMe创建的JSON文件包含了丰富的元数据,包括但不限于图像尺寸、形状列表及其属性等。对于语义分割任务而言,重点在于提取多边形坐标以及对应的类别名称[^1]。 ```python import json from PIL import Image, ImageDraw def parse_labelme_json(json_file_path): with open(json_file_path, 'r', encoding='utf-8') as f: data = json.load(f) image_width = data['imageWidth'] image_height = data['imageHeight'] shapes = [] for shape in data['shapes']: points = [(point[0], point[1]) for point in shape["points"]] label = shape["label"] shapes.append((label, points)) return (image_width, image_height), shapes ``` #### 创建掩码图像 基于上述解析得到的信息,可以构建相应的二值化或彩色编码的掩码图像作为监督信号的一部分。这里展示了一个简单的函数来绘制给定轮廓上的像素点: ```python def create_mask(image_size, parsed_shapes, output_image_path=None): mask_img = Image.new('L', (image_size[0], image_size[1]), color=0) draw = ImageDraw.Draw(mask_img) for label, polygon_points in parsed_shapes: # 假设不同类别的颜色映射已定义好 class_id = get_class_id(label) # 用户自定义获取ID的方法 fill_color = int(class_id * 255 / max_classes_count()) # 或者其他方式指定颜色 draw.polygon(polygon_points, outline=fill_color, fill=fill_color) if output_image_path is not None: mask_img.save(output_image_path) return mask_img ``` #### 批量处理脚本 考虑到实际应用中可能面对大量图片及对应标注的情况,编写批处理程序能够显著提高效率。下面是一个用于遍历目录内所有`.json`文件并执行前述操作的例子: ```bash for file_name in *.json; do base="${file_name%.*}" python convert_script.py \ --input-json "$base.json" \ --output-mask "masks/${base}_mask.png" done ``` 其中`convert_script.py`即包含之前提到的功能模块;而命令行参数则指定了输入输出路径以便灵活调整工作流设置。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值