图像分割之json转为mask图像

import json
import os
import os.path as osp
import base64
import warnings
from PIL import Image

# import PIL.Image
import yaml
from labelme import utils
import cv2
import numpy as np
from skimage import img_as_ubyte


def main(json_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.")
    # json文件加入列表
    list_path = []
    for json_single in os.listdir(json_file):
        if json_single.endswith('.json'):
            list_path.append(json_single)

    for i in range(0, len(list_path)):
        # 挨个读取json文件
        path = os.path.join(json_file, list_path[i])
        if os.path.isfile(path):
            data = json.load(open(path,encoding='utf-8'))
            img = utils.img_b64_to_arr(data['imageData'])
            print('imagedata: ', data['imageData'])
            print('datashape: ', data['shapes'])
            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(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(json_file + 'mask'):
                os.mkdir(json_file + 'mask')
            maskdir = json_file + 'mask'

            if not osp.exists(json_file + 'mask_viz'):
                os.mkdir(json_file + 'mask_viz')
            maskvizdir = json_file + 'mask_viz'
            out_dir1 = maskdir

            # 保存
            Image.fromarray(lbl).save(out_dir1 + '/' + save_file_name + '.png')
            Image.fromarray(lbl_viz).save(maskvizdir + '/' + save_file_name + '_label_viz.png')

            with open(osp.join(out_dir1, '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_dir1, 'info.yaml'), 'w') as f:
                yaml.safe_dump(info, f, default_flow_style=False)
            print('Saved to: %s' % out_dir1)


if __name__ == '__main__':
    json_file = r"F:\个人实验代码\study\test\json"
    main(json_file)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你有一个语义分割的JSON文件,其中包含个像素的标注信息,你可以将其换为gaug库支持的语义分割掩码格式。下面是将JSON文件换为Imgaug格式的步: 1. 读取文件并解析标数据,使用Pythonjson库将JSON文件取为Python对象。假设你的JSON文件名为 "annotations.json",可以使用以下代码读取和解析文件: ```python import json with open('annotations.json', 'r') as f: data = json.load(f) ``` 2. 定义一个函数或使用适当的方法,将标注数据换为Imgaug格式。Imgaug库支持使用语义分割掩码表示图像的标注。你需要将从JSON文件中提取的标注数据换为这种格式。以下是一个示例函数,可以将JSON文件中的语义分割标注数据换为Imgaug格式: ```python import imgaug as ia from imgaug.augmentables.segmaps import SegmentationMapOnImage def convert_annotations(data): annotations = [] for sample in data: image_path = sample['image_path'] mask_data = sample['mask_data'] mask = SegmentationMapOnImage(mask_data, shape=image_path.shape) annotation_dict = {'image': image_path, 'segmentation_maps': mask} annotations.append(annotation_dict) return annotations ``` 上述代码假设每个标注样本都有一个'image_path'键,表示图像文件路径,以及一个'mask_data'键,表示该图像的语义分割掩码数据。 3. 最后,将换后的标注数据保存为Imgaug支持的文件格式(如pickle)。你可以使用Imgaug库提供的方法来保存标注数据。以下是一个示例代码: ```python import pickle annotations = convert_annotations(data) with open('annotations.pkl', 'wb') as f: pickle.dump(annotations, f) ``` 上述代码将换后的标注数据保存为名为 "annotations.pkl" 的pickle文件。 请注意,以上代码仅提供了一个示例,你需要根据你的JSON文件结构和需求进行相应的修改。另外,你可能还需要安装Imgaug库和其他必要的依赖项。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值