如何通过labelme标注将json文件转为png的label

2021-06-21 17:56:56 浏览数 (1)

1、安装labelme

1、创建一个新环境

代码语言:javascript复制
conda create -n labelme python=3.6

2、进入该环境,安装pyqt5和labelme,labelme要求3.3.1的版本

代码语言:javascript复制
pip install pyqt5 -i https://pypi.doubanio.com/simple
代码语言:javascript复制
pip install labelme==3.3.1 -i https://pypi.doubanio.com/simple 

3、安装完成后,直接输入labelme,打开labelme软件即可

代码语言:javascript复制
labelme

至于怎么使用就不说了,应该很简单,保存crtl s保存的是json文件

下面说说如何将json文件转为png的label

2、文件转换

首先要注意的是,有些该导入的包还是要自己先导入的,比说说什么pillow等。下载的时候,加个镜像源 -i https://pypi.doubanio.com/simple 1)定位到Anaconda的安装目录D:SoftwareanacondaLibsite-packages 在site_pakeages下找到lableme的文件夹:

进入到cli文件夹,找到json_to_dataset.py文件,将里面的代码替换成如下:

代码语言:javascript复制
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import argparse
import json
import os
import os.path as osp
import base64
import warnings

import PIL.Image
import yaml

from labelme import utils

import cv2
import numpy as np
from skimage import img_as_ubyte


# from sys import argv

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

    list_path = os.listdir(json_file)

    for i in range(0, len(list_path)):
        if list_path[i].endswith('.json'):
            path = os.path.join(json_file, list_path[i])
            if os.path.isfile(path):

                data = json.load(open(path))
                img = utils.img_b64_to_arr(data['imageData'])
                lbl, lbl_names = utils.labelme_shapes_to_label(img.shape, data['shapes'])

                captions = ['%d: %s' % (l, name) for l, name in enumerate(lbl_names)]

                lbl_viz = utils.draw_label(lbl, img, captions)
                save_file_name = osp.basename(path).replace('.', '_')

                out_dir1 = osp.join(osp.dirname(path), 'labelme_results')
                if not osp.exists(out_dir1):
                    os.mkdir(out_dir1)
                out_dir1 = osp.join(out_dir1, save_file_name)
                if not osp.exists(out_dir1):
                    os.mkdir(out_dir1)

                PIL.Image.fromarray(img).save(out_dir1   '\'   save_file_name   '_img.png')
                PIL.Image.fromarray(lbl).save(out_dir1   '\'   save_file_name   '_label.png')

                PIL.Image.fromarray(lbl_viz).save(out_dir1   '\'   save_file_name  
                                                  '_label_viz.png')
                images_dir = osp.join(json_file, 'images_dir')
                if not osp.exists(images_dir):
                    os.mkdir(images_dir)
                labels_dir = osp.join(json_file, 'labels_dir')
                if not osp.exists(labels_dir):
                    os.mkdir(labels_dir)
                PIL.Image.fromarray(img).save(osp.join(images_dir, '{}_img.png'.format(save_file_name)))
                PIL.Image.fromarray(lbl).save(osp.join(labels_dir, '{}_label.png'.format(save_file_name)))

                with open(osp.join(out_dir1, 'label_names.txt'), 'w') as f:
                    for lbl_name in lbl_names:
                        f.write(lbl_name   'n')

                info = dict(label_names=lbl_names)
                with open(osp.join(out_dir1, 'info.yaml'), 'w') as f:
                    yaml.safe_dump(info, f, default_flow_style=False)

                print('Saved to: %s' % out_dir1)


if __name__ == '__main__':
    # base64path = argv[1]
    main()

点击运行,出现以下错误没事。。属于正常

错误:numpy版本太高(numpy需要版本为1.15.0)

2)将utils中的文件夹中的shape.py中的文件内容改成以下:

代码语言:javascript复制
from skimage import img_as_ubyte
import numpy as np
import PIL.Image
import PIL.ImageDraw

from labelme import logger


def polygons_to_mask(img_shape, polygons):
    mask = np.zeros(img_shape[:2], dtype=np.uint8)
    mask = PIL.Image.fromarray(mask)
    xy = list(map(tuple, polygons))
    PIL.ImageDraw.Draw(mask).polygon(xy=xy, outline=1, fill=1)
    mask = np.array(mask, dtype=bool)
    return mask


def shapes_to_label(img_shape, shapes, label_name_to_value, type='class'):
    assert type in ['class', 'instance']

    cls = np.zeros(img_shape[:2], dtype=np.int32)
    if type == 'instance':
        ins = np.zeros(img_shape[:2], dtype=np.int32)
        instance_names = ['_background_']
    for shape in shapes:
        polygons = shape['points']
        label = shape['label']
        if type == 'class':
            cls_name = label
        elif type == 'instance':
            cls_name = label.split('-')[0]
            if label not in instance_names:
                instance_names.append(label)
            ins_id = len(instance_names) - 1
        cls_id = label_name_to_value[cls_name]
        mask = polygons_to_mask(img_shape[:2], polygons)
        cls[mask] = cls_id
        if type == 'instance':
            ins[mask] = ins_id

    if type == 'instance':
        return cls, ins
    return cls


def labelme_shapes_to_label(img_shape, shapes):
    logger.warn('labelme_shapes_to_label is deprecated, so please use '
                'shapes_to_label.')

    label_name_to_value = {'_background_': 0}  # 注意:需要改成自己的类别
    for shape in shapes:
        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 = shapes_to_label(img_shape, shapes, label_name_to_value)
    lbl = img_as_ubyte(lbl)
    return lbl, label_name_to_value

运行,没出现错误即可

3)进入D:SoftwareanacondaScripts下找到labelme_json_to_dataset.exe 在相应的环境下输入 labelme_json_to_dataset.exe C:Users86152Desktopjson 后面的这个路径代表的是 存放json文件的路径

已经转换完成!!! 存放的png文件在C:Users86152Desktopjsonlabelme_resultsID_0011_Z_0156_json下面

在这个label_names.txt文件中保存的是分的类别,这样就可以了,成功!!

0 人点赞