Labelme 批量转 dataset 使用 labelme_json_to_dataset 命令 (简明图文教程)

实验环境

操作系统:Windows 10
Python:3.8
Labelme:4.5.13 (这个版本比较重要,不同版本代码可能会不一样)
Anaconda:4.10.1

如果还有同学没有安装好 Anaconda,或者 Labelme 请参见,我的另外两篇文章:安装Anaconda,安装 Labelme

0.概述

    现有的标注 json 文件转 dataset 的工具只能转单个 json 文件,没有办法批量转多个标注文件。本文中笔者根据转换原理修改相关代码实现了批量转换一个目录下所有 json 文件的方法,该方法支持输入一个目录,并且兼容 -o, --out 参数来指定输出 dataset 的目录,详细介绍如下。

1.原理

默认安装的 Labelme 有个可以单个转换 json 标注文件成 dataset 的工具,在 $python目录\Scripts 下,例如:

Anaconda虚拟环境
D:\anaconda3\envs\labelme\Scripts\labelme_json_to_dataset.exe
非虚拟环境
E:\python\Python37\Scripts\labelme_json_to_dataset.exe

这个exe文件,调用的代码是 $python目录\Lib\site-packages\labelme\cli\json_to_dataset.py ,例如

Anaconda虚拟环境
D:\anaconda3\envs\labelme\Lib\site-packages\labelme\cli\json_to_dataset.py
非虚拟环境
E:\python\Python37\Lib\site-packages\labelme\cli\json_to_dataset.py

执行命令

(labelme) PS D:\anaconda3\envs\labelme\Scripts> .\labelme_json_to_dataset.exe E:\annotation\xx.json --out E:\xxx

1. 参数1:标注文件 xx.json
2. 参数2: --out 输出目录

但是这个只能转单个文件,因此就要修改json_to_dataset.py代码,从转一个文件改成修改多个文件

2.代码

我的这个代码是在Labelme 4.5.13 下修改的,如果同学是这个版本,可以直接使用。如果不是,可以详细看下中文注释,请切记在你自己的文件上修改,要不会出现各种奇怪的问题。
主要思路是在读取完第一个参数后,把参数当成一个目录,读取里面的所有文件,然后循环转换,核心代码如下:

filelist = os.listdir(json_file)  # 输入的参数当成目录,取得目录下的所有 json 文件
for i in range(0, len(filelist)):  # 遍历文件列表
    path = os.path.join(json_file, filelist[i])  # 单个文件路径
    if os.path.isdir(path):  # 如果是目录则读取下一个
        continue
    my_out = osp.basename(filelist[i]).replace(".", "_")  # 文件名转目录
    if args.out is None:
        # out_dir = osp.basename(json_file).replace(".", "_")  # 注释掉
        out_dir = osp.join(osp.dirname(json_file), my_out)   # 总目录 + 文件目录
    else:
        # out_dir = args.out # 注释掉
        if not osp.exists(args.out): # 兼容目录不存在情况
            os.makedirs(args.out)
        out_dir = osp.join(args.out, my_out)  # 兼容out参数  --  总目录 + 文件目录
    if not osp.exists(out_dir):
        os.mkdir(out_dir)

完成代码如下:

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():
    logger.warning(
        "This script is aimed to demonstrate how to convert the "
        "JSON file to a single image dataset."
    )
    logger.warning(
        "It won't handle multiple JSON files to generate a "
        "real-use dataset."
    )

    parser = argparse.ArgumentParser()
    parser.add_argument("json_file")
    parser.add_argument("-o", "--out", default=None)
    args = parser.parse_args()

    json_file = args.json_file

    filelist = os.listdir(json_file)  # 文件列表
    for i in range(0, len(filelist)):  # 遍历文件列表
        path = os.path.join(json_file, filelist[i])  # 文件路径
        if os.path.isdir(path):  #如果是目录则读取下一个
            continue
        my_out = osp.basename(filelist[i]).replace(".", "_")  # 文件名转目录
        if args.out is None:
            # out_dir = osp.basename(json_file).replace(".", "_")  # 注释掉
            out_dir = osp.join(osp.dirname(json_file), my_out)   # 总目录 + 文件目录
        else:
            # out_dir = args.out # 注释掉
            if not osp.exists(args.out): # 兼容目录不存在情况
                os.makedirs(args.out)
            out_dir = osp.join(args.out, my_out)  # 兼容out参数  --  总目录 + 文件目录
        if not osp.exists(out_dir):
            os.mkdir(out_dir)

        data = json.load(open(path))   # 读取目录标注文件
        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}
        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()

3.试验过程

打开这个,进入conda的命令行:
在这里插入图片描述
进入 labelme_json_to_dataset.exe 目录

(base) PS C:\Users\xxx> d:
(base) PS D:\> cd D:\anaconda3\envs\labelme\Scripts\

进入labelme 的虚拟环境

(base) PS D:\anaconda3\envs\labelme\Scripts> conda activate labelme
(labelme) PS D:\anaconda3\envs\labelme\Scripts>

3.1 实验一:输入单个目录

标注文件目录 E:\annotation
在这里插入图片描述
执行命令:

(labelme) PS D:\anaconda3\envs\labelme\Scripts> .\labelme_json_to_dataset.exe E:\annotation\

在这里插入图片描述
生成的文件:
在这里插入图片描述

3.2 实验二: 增加参数 --out 输出文件目录

执行命令:

 (labelme) PS D:\anaconda3\envs\labelme\Scripts> .\labelme_json_to_dataset.exe E:\annotation\ --out E:\xxx

在这里插入图片描述
在这里插入图片描述

4.方法二

还有网友提出可以通过批处理文件进行批量的转换,我也做了实验,相关脚本和实验过程如下:

4.1 重新创建虚拟环境

创建名叫 labelme2 的虚拟环境

(base) PS C:\Users\xxx> conda create -n labelme2 python=3.8

在这里插入图片描述

4.2 进入虚拟环境和标注目录:

(base) PS C:\Users\xxx> conda activate labelme2
(labelme2) PS C:\Users\xxx> e:
(labelme2) PS E:\annotation> cd E:\annotation\

4.3 安装labelme的依赖

conda install pillow
conda install pyqt

4.4 安装labelme

pip install labelme

4.5 编写bat文件

将下列代码保存到txt中,存放到你的json目录下,改后缀为.bat

@echo off
for %%i in (*.json) do D:\anaconda3\envs\labelme2\Scripts\labelme_json_to_dataset "%%i"
pause

在这里插入图片描述
执行bat

(labelme2) PS E:\annotation> .\conver.bat

结果如下:
在这里插入图片描述

在这里插入图片描述
欢迎有问题的小伙伴留言讨论,o( ̄︶ ̄)o

参考:
[1]. 实现labelme批量json_to_dataset方法
[2]. labelme标签批量转换,labelme_json_to_dataset

  • 35
    点赞
  • 112
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 19
    评论
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

炼丹狮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值