labelme2seg.py 2.9 KB
Newer Older
W
wuzewu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#!/usr/bin/env python

from __future__ import print_function

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

import numpy as np
import PIL.Image
import labelme

L
LutaoChu 已提交
15 16
from pdseg.vis import get_color_map_list

W
wuzewu 已提交
17

18
def parse_args():
W
wuzewu 已提交
19 20 21
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
22 23 24 25 26 27 28 29 30 31
    parser.add_argument('input_dir',
                        help='input annotated directory')
    return parser.parse_args()


def main(args):
    output_dir = osp.join(args.input_dir, 'annotations')
    if not osp.exists(output_dir):
        os.makedirs(output_dir)
        print('Creating annotations directory:', output_dir)
W
wuzewu 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45

    # get the all class names for the given dataset
    class_names = ['_background_']
    for label_file in glob.glob(osp.join(args.input_dir, '*.json')):
        with open(label_file) as f:
            data = json.load(f)
            for shape in data['shapes']:
                label = shape['label']
                cls_name = label
                if not cls_name in class_names:
                    class_names.append(cls_name)

    class_name_to_id = {}
    for i, class_name in enumerate(class_names):
46
        class_id = i  # starts with 0
W
wuzewu 已提交
47 48 49 50 51 52
        class_name_to_id[class_name] = class_id
        if class_id == 0:
            assert class_name == '_background_'
    class_names = tuple(class_names)
    print('class_names:', class_names)

53
    out_class_names_file = osp.join(args.input_dir, 'class_names.txt')
W
wuzewu 已提交
54 55 56 57
    with open(out_class_names_file, 'w') as f:
        f.writelines('\n'.join(class_names))
    print('Saved class_names:', out_class_names_file)

L
LutaoChu 已提交
58 59
    color_map = get_color_map_list(256)

W
wuzewu 已提交
60 61 62 63 64
    for label_file in glob.glob(osp.join(args.input_dir, '*.json')):
        print('Generating dataset from:', label_file)
        with open(label_file) as f:
            base = osp.splitext(osp.basename(label_file))[0]
            out_png_file = osp.join(
65
                output_dir, base + '.png')
W
wuzewu 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79

            data = json.load(f)

            img_file = osp.join(osp.dirname(label_file), data['imagePath'])
            img = np.asarray(PIL.Image.open(img_file))

            lbl = labelme.utils.shapes_to_label(
                img_shape=img.shape,
                shapes=data['shapes'],
                label_name_to_value=class_name_to_id,
            )

            if osp.splitext(out_png_file)[1] != '.png':
                out_png_file += '.png'
80
            # Assume label ranges [0, 255] for uint8,
W
wuzewu 已提交
81
            if lbl.min() >= 0 and lbl.max() <= 255:
L
LutaoChu 已提交
82 83
                lbl_pil = PIL.Image.fromarray(lbl.astype(np.uint8), mode='P')
                lbl_pil.putpalette(color_map)
W
wuzewu 已提交
84 85 86 87 88 89 90
                lbl_pil.save(out_png_file)
            else:
                raise ValueError(
                    '[%s] Cannot save the pixel-wise class label as PNG. '
                    'Please consider using the .npy format.' % out_png_file
                )

91

W
wuzewu 已提交
92
if __name__ == '__main__':
93 94
    args = parse_args()
    main(args)