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 osp
import imgviz
import PIL.Image
import numpy as np
from PIL import Image
from labelme.logger import logger
from labelme import utils
def 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.json
out_dir = osp.basename(file_name).replace(".", "_") # 1_dir
out_dir = osp.join(json_dir, out_dir)
if not osp.exists(out_dir):
os.mkdir(out_dir) # E:\roadSegmentation\images\1_dir
path = osp.join(json_dir, file_name) # E:\roadSegmentation\images\1.json
if 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.png
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 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(
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
该路径下,再试试。