可用于方便的将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)