使用 anaconda 提示符将批量 Labelme json 文件转换为一组图像和标签

我有一个由 Labelme 工具生成为 JSON 文件的图像掩码数据集,在 Github 教程(https://github.com/wkentaro/labelme/tree/master/examples/tutorial)上它显示更改 JSON 文件进入图像文件,我们使用以下命令行代码


labelme_json_to_dataset apc2016_obj3.json -o apc2016_obj3_json

但是这一次只适用于一个文件,所以我一直在尝试找到一种使用一组代码处理所有文件的方法,我尝试了以下代码


setlocal

set "yourDir=C:\Users\Acer\Desktop\datasets\combined masks\"

set "yourExt=*.json"

pushd %yourDir%

for %%a in (*%yourExt%)do labelme_json_to_dataset %%a -o %%a

popd

endlocal

该代码现在通过读取文件名并添加文件扩展名 .json 来工作,但是,将文件保存到具有相同名称的目录(包括 .json 扩展名)会给我以下错误


Traceback (most recent call last):

  File "c:\users\acer\.conda\envs\labelme\lib\runpy.py", line 193, in _run_module_as_main

    "__main__", mod_spec)

  File "c:\users\acer\.conda\envs\labelme\lib\runpy.py", line 85, in _run_code

    exec(code, run_globals)

  File "C:\Users\ACER\.conda\envs\labelme\Scripts\labelme_json_to_dataset.exe\__main__.py", line 7, in <module>

  File "c:\users\acer\.conda\envs\labelme\lib\site-packages\labelme\cli\json_to_dataset.py", line 65, in main

    PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))

  File "c:\users\acer\.conda\envs\labelme\lib\site-packages\PIL\Image.py", line 2131, in save

    fp = builtins.open(filename, "w+b")

FileNotFoundError: [Errno 2] No such file or directory: '000828.json\\img.png'

我不熟悉 cmd,需要帮助将输出保存到文件名不带 .json 扩展名的目录


下面是一个单个文件示例,它显示了成功运行应该是什么样子 在此处输入图像描述


(labelme) C:\Users\ACER\Desktop\datasets\combined masks>labelme_json_to_dataset 000814.json -o 000814

[[1m[33mWARNING[0m] [36mjson_to_dataset[0m:[36mmain[0m:[36m15[0m - [1m[33mThis script is aimed to demonstrate how to convert the JSON file to a single image dataset.[0m

[[1m[33mWARNING[0m] [36mjson_to_dataset[0m:[36mmain[0m:[36m17[0m - [1m[33mIt won't handle multiple JSON files to generate a real-use dataset.[0m

[[1m[37mINFO   [0m] [36mjson_to_dataset[0m:[36mmain[0m:[36m73[0m - [1m[37mSaved to: 000814[0m


(labelme) C:\Users\ACER\Desktop\datasets\combined masks>


慕容708150
浏览 272回答 4
4回答

海绵宝宝撒

使用命令FOR /?阅读substitution of FOR variable references帮助输出的最后一页。要获取文件的基本名称,%%~na可以使用。在没有的情况下运行它,ECHO OFF以便您可以看到每个命令。setlocalset "yourDir=C:\Users\Acer\Desktop\datasets\combined masks\"set "yourExt=*.json"pushd %yourDir%for %%a in (*%yourExt%) do (labelme_json_to_dataset %%a -o %%~na)popdendlocal

阿晨1998

import labelmeimport os, syspath="path/to/directory"dirs = os.listdir(path)i=0for item in dirs:&nbsp; &nbsp;if item.endswith(".json"):&nbsp; &nbsp; &nbsp; if os.path.isfile(path+item):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;my_dest ="fin" + str(i)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;os.system("mkdir "+my_dest)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;os.system("labelme_json_to_dataset "+item+" -o "+my_dest)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;i=i+1

largeQ

for&nbsp;/l&nbsp;%n&nbsp;in&nbsp;(2,1,50)&nbsp;do&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;(labelme_json_to_dataset&nbsp;images%n.json&nbsp;-o&nbsp;images%n)每个file.json空白文件夹(之前为保存数据集而准备的)都在同一个文件夹中(使用此代码的当前目录)。

SMILET

这个解决方案并不完美,只是生成了遮罩和覆盖 png 文件。它也只是保留文件名。import argparseimport base64import jsonimport osimport os.path as ospimport imgvizimport PIL.Imagefrom labelme.logger import loggerfrom labelme import utilsdef main():&nbsp; &nbsp; parser = argparse.ArgumentParser()&nbsp; &nbsp; parser.add_argument("json_file")&nbsp; &nbsp; parser.add_argument("-o", "--out", default=None)&nbsp; &nbsp; args = parser.parse_args()&nbsp; &nbsp; json_file = args.json_file&nbsp; &nbsp; if args.out is None:&nbsp; &nbsp; &nbsp; &nbsp; out_dir = osp.basename(json_file).replace(".", "_")&nbsp; &nbsp; &nbsp; &nbsp; out_dir = osp.join(osp.dirname(json_file), out_dir)&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; out_dir = args.out&nbsp; &nbsp; if not osp.exists(out_dir):&nbsp; &nbsp; &nbsp; &nbsp; os.mkdir(out_dir)&nbsp; &nbsp; data = json.load(open(json_file))&nbsp; &nbsp; imageData = data.get("imageData")&nbsp; &nbsp; if not imageData:&nbsp; &nbsp; &nbsp; &nbsp; imagePath = os.path.join(os.path.dirname(json_file), data["imagePath"])&nbsp; &nbsp; &nbsp; &nbsp; print(imagePath)&nbsp; &nbsp; &nbsp; &nbsp; with open(imagePath, "rb") as f:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; imageData = f.read()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; imageData = base64.b64encode(imageData).decode("utf-8")&nbsp; &nbsp; img = utils.img_b64_to_arr(imageData)&nbsp; &nbsp; label_name_to_value = {"_background_": 0}&nbsp; &nbsp; for shape in sorted(data["shapes"], key=lambda x: x["label"]):&nbsp; &nbsp; &nbsp; &nbsp; label_name = shape["label"]&nbsp; &nbsp; &nbsp; &nbsp; if label_name in label_name_to_value:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; label_value = label_name_to_value[label_name]&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; label_value = len(label_name_to_value)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; label_name_to_value[label_name] = label_value&nbsp; &nbsp; lbl, _ = utils.labelme_shapes_to_label(img.shape, data["shapes"])&nbsp; &nbsp; label_names = [None] * (max(label_name_to_value.values()) + 1)&nbsp; &nbsp; for name, value in label_name_to_value.items():&nbsp; &nbsp; &nbsp; &nbsp; label_names[value] = name&nbsp; &nbsp; lbl_viz = imgviz.label2rgb(&nbsp; &nbsp; &nbsp; &nbsp; lbl, imgviz.asgray(img), label_names=label_names, loc="rb"&nbsp; &nbsp; )&nbsp; &nbsp; filename = str(json_file).split('.')[1]&nbsp; &nbsp; utils.lblsave(osp.join(out_dir, f'.{filename}.png'), lbl)&nbsp; &nbsp; PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, f'.{filename}_viz.png'))&nbsp; &nbsp; logger.info("Saved to: {}".format(out_dir))if __name__ == "__main__":&nbsp; &nbsp; main()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python