图像分割 json文件 批量转mask

图像分割 json文件 批量转mask

在进行labelme进行标注后有大量json文件,如果做图像分割需要转为mask才能进入进行训练

1.下载labelme
去github上搜索labelme,用git clone 下载

2.修改json_to_dataset.py 文件路径:label/label/cil/json_to_dataset.py

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

import imgviz
import PIL.Image

from labelme.logger import logger
from labelme import utils


def main(file, outfile):
    logger.warning(
        "This script is aimed to demonstrate how to convert the "
        "JSON file to a single image dataset."
    )
    logger.warning(
        "It won't handle multiple JSON files to generate a "
        "real-use dataset."
    )

    parser = argparse.ArgumentParser()
    parser.add_argument("--json_file", default=file)
    parser.add_argument("-o", "--out", default=outfile)
    args = parser.parse_args()

    json_file = args.json_file

    if args.out is None:
        out_dir = osp.basename(json_file).replace(".", "_")
        out_dir = osp.join(osp.dirname(json_file), out_dir)
    else:
        out_dir = args.out
    if not osp.exists(out_dir):
        os.mkdir(out_dir)

    data = json.load(open(json_file))
    imageData = data.get("imageData")

    if not imageData:
        imagePath = os.path.join(os.path.dirname(json_file), data["imagePath"].split("/")[-1])
        
        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 sorted(data["shapes"], key=lambda x: x["label"]):
        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
    lbl, _ = utils.shapes_to_label(
        img.shape, data["shapes"], label_name_to_value
    )

    label_names = [None] * (max(label_name_to_value.values()) + 1)
    for name, value in label_name_to_value.items():
        label_names[value] = name

    lbl_viz = imgviz.label2rgb(
        label=lbl, img=imgviz.asgray(img), label_names=label_names, loc="rb"
    )

    PIL.Image.fromarray(img).save(osp.join(out_dir, "img.png"))
    utils.lblsave(osp.join(out_dir, "label.png"), lbl)
    PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, "label_viz.png"))

    with open(osp.join(out_dir, "label_names.txt"), "w") as f:
        for lbl_name in label_names:
            f.write(lbl_name + "\n")

    logger.info("Saved to: {}".format(out_dir))


if __name__ == "__main__":
    import os
    import os.path as osp
    json_path = "../SR-line/" #json文件路径
    out_path = "../SR-line_vis/" #输出mask保存文件路径
    os.makedirs(out_path, exist_ok=True)
    for file in os.listdir(json_path):
        if ".json" in file:
            main(osp.join(json_path, file), osp.join(out_path, file.split(".")[0]))

修改完后在json_to_dataset.py路径下运行:python json_to_dataset.py (第一次运行过程中缺什么包安装什么包:pip install [缺少的包] 即可)

在这里插入图片描述
保存结果:

生成四张结果图在这里插入图片描述

备注:
1.mask是8bit,原图是24bit,需要正确的图片格式输入网络才能正确训练,否则模型无法正确学习
2.文件保存格式和路径可以适当修改json_to_dataset.py里面的代码

简单版:

"""
将用labelme分割打标工具打标获取的json文件批量转换为mask(annotation)图及对应图片

"""

# import argparse
import base64
import json
import os
import os.path as osp
import uuid

import imgviz
import PIL.Image
from labelme import utils

if __name__ == "__main__":

    base_dir = osp.dirname(osp.abspath(__file__))

    out_dir_name = "out_data"
    out_dir = osp.join(base_dir, out_dir_name)
    if not osp.exists(out_dir):
        os.mkdir(out_dir)
    label_names = []
    label_file = "./label_names.txt"
    label_value_dict = {}
    with open(label_file) as f:
        labels = f.readlines()
        if len(labels) > 0:
            for i, item in enumerate(labels):
                item = item.strip()
                label_value_dict[item] = i

    json_file_name = "jsons"  #'cityspaces'
    json_file_path = osp.join(base_dir, json_file_name)
    new_filename = 1
    for file_name in os.listdir(json_file_path):
        print(file_name)
        if file_name.endswith(".json"):
            filePath = osp.join(json_file_path, file_name)
            data = json.load(open(filePath))
            imageData = data.get("imageData")
            if not imageData:
                imagePath = os.path.join(os.path.dirname(filePath),
                                         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)

            for shape in sorted(data["shapes"], key=lambda x: x["label"]):
                label_name = shape["label"]
                if label_name not in label_value_dict:
                    label_value = len(label_value_dict)
                    label_value_dict[label_name] = label_value

            lbl, _ = utils.shapes_to_label(img.shape, data["shapes"],
                                           label_value_dict)

            label_names = [None] * (max(label_value_dict.values()) + 1)
            for name, value in label_value_dict.items():
                label_names[value] = name

            lbl_viz = imgviz.label2rgb(lbl,
                                       imgviz.asgray(img),
                                       label_names=label_names,
                                       loc="rb")

            #new_filename = uuid.uuid4().hex

            PIL.Image.fromarray(img).save(
                osp.join(out_dir,
                         str(new_filename) + "_img.png"))
            utils.lblsave(
                osp.join(out_dir,
                         str(new_filename) + "_label" + ".png"), lbl)
            new_filename = new_filename + 1
            #PIL.Image.fromarray(lbl_viz).save(
            #    osp.join(out_dir, new_filename + "_label_viz" + ".png"))

    for name, value in label_value_dict.items():
        label_names[value] = name

    with open("./label_names.txt", "w") as f:
        for lbl_name in label_names:
            f.write(lbl_name + "\n")

#
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你有一个语义分割JSON文件,其中包含个像素的标注信息,你可以将其换为gaug库支持的语义分割掩码格式。下面是将JSON文件换为Imgaug格式的步: 1. 读取文件并解析标数据,使用Python的json库将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、付费专栏及课程。

余额充值