当前位置: 首页> 科技> 名企 > labelme:将json格式的标注文件(批量)转换为png可视化图片(且确保同一类物体的颜色相同)

labelme:将json格式的标注文件(批量)转换为png可视化图片(且确保同一类物体的颜色相同)

时间:2025/7/16 19:16:30来源:https://blog.csdn.net/weixin_45720626/article/details/141639600 浏览次数:0次

labelme:将json格式的标注文件(批量)转换为png可视化图片(且确保同一类物体的颜色相同)

       代码主要是根据官方代码稍作修改得来的:D:\Program_Files\anaconda3\envs\labelme\Lib\site-packages\labelme\cli
在该目录下有json_to_dataset.py文件(该文件一次只能转换一份json文件,且转换多份json文件不能确保同一类物体的颜色一定相同),主要就是依据该文件的代码。

       创建文件json_to_dataset_batch_DIY.py

import argparse
import base64
import json
import os
import os.path as ospimport imgviz
import PIL.Imageimport numpy as np
from PIL import Imagefrom labelme.logger import logger
from labelme import utilsdef main():logger.warning("This script is aimed to demonstrate how to convert the ""JSON file to a single image dataset.")logger.warning("It can handle multiple JSON files to generate a ""real-use dataset.")# json文件的目录路径json_dir = r"E:\roadSegmentation\images"# 谨记,此行代码一定要放到下面的循环之前label_name_to_value = {"_background_": 0}for file_name in os.listdir(json_dir):if file_name.endswith(".json"):# file_name = 1.jsonout_dir = osp.basename(file_name).replace(".", "_")  # 1_dirout_dir = osp.join(json_dir, out_dir)if not osp.exists(out_dir):os.mkdir(out_dir)  # E:\roadSegmentation\images\1_dirpath = osp.join(json_dir, file_name)  # E:\roadSegmentation\images\1.jsonif osp.isfile(path):data = json.load(open(path))imageData = data.get("imageData")if not imageData:imagePath = osp.join(json_dir, data["imagePath"])  # E:\roadSegmentation\images\1.pngwith 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 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_valuelbl, _ = 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] = namelbl_viz = imgviz.label2rgb(lbl, 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__":main()

json文件的目录路径改好,运行代码就可以了。如果不行,就把该py文件放在D:\Program_Files\anaconda3\envs\labelme\Lib\site-packages\labelme\cli该路径下,再试试。

关键字:labelme:将json格式的标注文件(批量)转换为png可视化图片(且确保同一类物体的颜色相同)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: