为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕容708150 2022-11-01 15:44:54
我有一个由 Labelme 工具生成为 JSON 文件的图像掩码数据集,在 Github 教程(https://github.com/wkentaro/labelme/tree/master/examples/tutorial)上它显示更改 JSON 文件进入图像文件,我们使用以下命令行代码labelme_json_to_dataset apc2016_obj3.json -o apc2016_obj3_json但是这一次只适用于一个文件,所以我一直在尝试找到一种使用一组代码处理所有文件的方法,我尝试了以下代码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 %%apopdendlocal该代码现在通过读取文件名并添加文件扩展名 .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>
查看完整描述

4 回答

?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

使用命令FOR /?阅读substitution of FOR variable references帮助输出的最后一页。要获取文件的基本名称,%%~na可以使用。在没有的情况下运行它,ECHO OFF以便您可以看到每个命令。


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 %%~na)

popd

endlocal


查看完整回答
反对 回复 2022-11-01
?
阿晨1998

TA贡献2037条经验 获得超6个赞

import labelme

import os, sys

path="path/to/directory"

dirs = os.listdir(path)

i=0

for item in dirs:

   if item.endswith(".json"):

      if os.path.isfile(path+item):

         my_dest ="fin" + str(i)

         os.system("mkdir "+my_dest)

         os.system("labelme_json_to_dataset "+item+" -o "+my_dest)

         i=i+1


查看完整回答
反对 回复 2022-11-01
?
largeQ

TA贡献2039条经验 获得超8个赞

for /l %n in (2,1,50) do 
    (labelme_json_to_dataset images%n.json -o images%n)

每个file.json空白文件夹(之前为保存数据集而准备的)都在同一个文件夹中(使用此代码的当前目录)。


查看完整回答
反对 回复 2022-11-01
?
SMILET

TA贡献1796条经验 获得超4个赞

这个解决方案并不完美,只是生成了遮罩和覆盖 png 文件。它也只是保留文件名。


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


    if args.out is None:

        out_dir = osp.basename(json_file).replace(".", "_")

        out_dir = osp.join(osp.dirname(json_file), out_dir)

    else:

        out_dir = args.out

    if not osp.exists(out_dir):

        os.mkdir(out_dir)


    data = json.load(open(json_file))

    imageData = data.get("imageData")


    if not imageData:

        imagePath = os.path.join(os.path.dirname(json_file), data["imagePath"])

        print(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}

    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.labelme_shapes_to_label(img.shape, data["shapes"])


    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"

    )


    filename = str(json_file).split('.')[1]

    utils.lblsave(osp.join(out_dir, f'.{filename}.png'), lbl)

    PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, f'.{filename}_viz.png'))


    logger.info("Saved to: {}".format(out_dir))



if __name__ == "__main__":

    main()


查看完整回答
反对 回复 2022-11-01
  • 4 回答
  • 0 关注
  • 271 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号