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

单一化处理

经过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()

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 当我们制作自己的图像分割数据集时,一般都需要对数据集进行像素级标注,生成mask(对应原图像的每个像素的类别图,一...
    Ziyun_Wang阅读 9,280评论 0 0
  • 一劳永逸的生活,我想每个人都会想过。 外婆前几年会问到“你毕业要分配到哪里?”,以前的工作都是包分配,大家对工作生...
    君好么阅读 961评论 3 2
  • 最近学习node,在做登录功能的时候接触到了redis,但是经常忘记redis常用的几个命令行,所以今天把我经常用...
    晚饭总吃撑阅读 436评论 0 1
  • 今天的走势,怎么说,和我的想法有些差别。上涨我是预料到了但13点后下来了,这就是没估计到的。 说几个好耍的事,一个...
    那一叶秋阅读 183评论 0 1
  • 外面不知何时又下起了雨,而我也不知道为什么特别喜欢雨。 因为雨带着清晰的空气的味道,而特别是黄昏的时候,我喜欢一个...
    曾宝弘阅读 277评论 0 3

友情链接更多精彩内容