栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Labelme库的json2dataset函数改写

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Labelme库的json2dataset函数改写

可用于方便的将json格式的标注文件转换为png、jpg等image文件。

如果是conda环境的话,pip install labelme之后,文件位置是:./envs/{ENV_NAME}/lib/python3.6/site-packages/labelme/cli/json_to_dataset.py

主要修改标注名到灰度值的映射字典label_name_to_value,无标注的默认为"_background_",还可以自由添加输出路径等。img为原图,lbl为转换后的灰度图,lbl_vis为混合原图与灰度图的可视化图。

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

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

    json_file = args.json_file

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

    if not imagedata:
        imagePath = os.path.join(os.path.dirname(json_file), 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,'60':1}
    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"
    )

    new_img_dir = '../img'
    new_gt_dir = '../gt'
    new_visable_dir = '../visable'
    name = json_file.split('/')[-1].split('.')[0]
    PIL.Image.fromarray(img).save(osp.join(new_img_dir, name+".png"))
    utils.lblsave(osp.join(new_gt_dir, name+".png"), lbl)
    PIL.Image.fromarray(lbl_viz).save(osp.join(new_visable_dir, name+".png"))

if __name__ == "__main__":
    main()

如下,通过python运行命令行批量调用,不过速度偏慢。

root = '../LabelJson'

FileNameList = os.listdir(root)
a = 0
for i in tqdm(range(len(FileNameList))):
    if(os.path.splitext(FileNameList[i])[1] == ".json"):   # 判断当前文件是否为json文件
        json_file = os.path.join(root,FileNameList[i])
        os.system("labelme_json_to_dataset " + json_file)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/580579.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号