美文网首页
批量化处理labelme 语义分割标注的文件

批量化处理labelme 语义分割标注的文件

作者: su945 | 来源:发表于2020-04-27 17:48 被阅读0次

单一化处理

经过labelme标注会生成和图像同样数据的json文件,在json文件下执行单个文件处理的命令

labelme_json_to_dataset ADE_train_00008815.json

会生成四个文件,分别为img.png,label.png,label.names.txt,label_viz.png.如图所示


img.png label.png label_viz.png
  • 注意不要认为只需要执行多次上述单个文件处理命令,就可以进行批量处理。同一标签在不同执行过程中会生成不同的颜色,主要原因是单步命令执行时,只按此图像中的标签类别个数进行分配颜色。因此这种方式无法进行批量化处理。

批量化处理

labelme仓库地址:https://github.com/wkentaro/labelme
在examples/semantic_segmentation路径下,可以参考README进行操作批量化处理。
即运行labelme2voc.py,会生成VOC格式文件目录。生成文件在SegmentationClassPNG文件下,保留了可视化比标注图片。
这种处理方式有个问题,是生成的label图像中标签位置的像素值并不是和lable类别名一致。在一些训练过程中,还需要进一步处理。因此可将代码修改如下:


from __future__ import print_function

import argparse
import glob
import os
import os.path as osp
import sys

import imgviz
import numpy as np

import labelme
import PIL.Image


def lblsave_unre(filename,out_png_unre_file, lbl):
    import imgviz

    if osp.splitext(filename)[1] != '.png':
        filename += '.png'
    # Assume label ranses [-1, 254] for int32,
    # and [0, 255] for uint8 as VOC.
    if lbl.min() >= -1 and lbl.max() < 255:
        lbl_pil = PIL.Image.fromarray(lbl.astype(np.uint8), mode='P')
        lbl_pil.save(out_png_unre_file)
        colormap = imgviz.label_colormap()
        lbl_pil.putpalette(colormap.flatten())
        lbl_pil.save(filename)
    else:
        raise ValueError(
            '[%s] Cannot save the pixel-wise class label as PNG. '
            'Please consider using the .npy format.' % filename
        )

def main():
    #标注文件路径
    input_dir = '/media/suyuan/U/data/annotation/select_0427/'
    #输出路径
    output_dir = '/media/suyuan/U/data/annotation/out_0427'
    #标签txt文件,里面含有按列排列的类别名
    labels = '/media/suyuan/U/data/annotation/labels_0427.txt'
    noviz = True


    if osp.exists(output_dir):
        print('Output directory already exists:', output_dir)
    else:
        os.makedirs(output_dir)
        os.makedirs(osp.join(output_dir, 'JPEGImages'))
        os.makedirs(osp.join(output_dir, 'SegmentationClass'))
        os.makedirs(osp.join(output_dir, 'SegmentationClassPNG'))
        if not noviz:
            os.makedirs(
                osp.join(output_dir, 'SegmentationClassVisualization')
            )
    print('Creating dataset:', output_dir)

    class_names = []
    class_name_to_id = {}
    for i, line in enumerate(open(labels).readlines()):
        class_id = i - 1  # starts with -1
        class_name = line.strip()
        class_name_to_id[class_name] = class_id
        if class_id == -1:
            assert class_name == '__ignore__'
            continue
        elif class_id == 0:
            assert class_name == '_background_'
        class_names.append(class_name)
    class_names = tuple(class_names)
    print('class_names:', class_names)
    out_class_names_file = osp.join(output_dir, 'class_names.txt')
    with open(out_class_names_file, 'w') as f:
        f.writelines('\n'.join(class_names))
    print('Saved class_names:', out_class_names_file)

    for filename in glob.glob(osp.join(input_dir, '*.json')):
        print('Generating dataset from:', filename)

        label_file = labelme.LabelFile(filename=filename)

        base = osp.splitext(osp.basename(filename))[0]
        out_img_file = osp.join(
            output_dir, 'JPEGImages', base + '.png')
        out_lbl_file = osp.join(
            output_dir, 'SegmentationClass', base + '.npy')
        out_png_file = osp.join(
            output_dir, 'SegmentationClassPNG', base + '.png')
        out_png_unre_file = osp.join(
            output_dir, 'SegmentationClassPNG', base + '_nyu.png')
        if not noviz:
            out_viz_file = osp.join(
                output_dir,
                'SegmentationClassVisualization',
                base + '.jpg',
            )

        with open(out_img_file, 'wb') as f:
            f.write(label_file.imageData)
        img = labelme.utils.img_data_to_arr(label_file.imageData)

        #
        lbl, _ = labelme.utils.shapes_to_label(
            img_shape=img.shape,
            shapes=label_file.shapes,
            label_name_to_value=class_name_to_id,
        )

        #labelme.utils.lblsave(out_png_file, lbl)
        lblsave_unre(out_png_file,out_png_unre_file,lbl)

        np.save(out_lbl_file, lbl)

        
        if not noviz:
            viz = imgviz.label2rgb(
                label=lbl,
                img=imgviz.rgb2gray(img),
                font_size=15,
                label_names= class_names,
                loc='rb',
            )
            imgviz.io.imsave(out_viz_file, viz)


if __name__ == '__main__':
    main()

相关文章

网友评论

      本文标题:批量化处理labelme 语义分割标注的文件

      本文链接:https://www.haomeiwen.com/subject/rzruwhtx.html