jingling2seg.py 3.8 KB
Newer Older
L
LutaoChu 已提交
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

15
from gray2pseudo_color import get_color_map_list
L
LutaoChu 已提交
16

L
LutaoChu 已提交
17

18
def parse_args():
L
LutaoChu 已提交
19
    parser = argparse.ArgumentParser(
L
LutaoChu 已提交
20 21
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('input_dir', help='input annotated directory')
22
    return parser.parse_args()
L
LutaoChu 已提交
23 24


25 26 27 28 29
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)
L
LutaoChu 已提交
30 31 32

    # get the all class names for the given dataset
    class_names = ['_background_']
33
    for label_file in glob.glob(osp.join(args.input_dir, '*.json')):
L
LutaoChu 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
        with open(label_file) as f:
            data = json.load(f)
            if data['outputs']:
                for output in data['outputs']['object']:
                    name = output['name']
                    cls_name = name
                    if not cls_name in class_names:
                        class_names.append(cls_name)

    class_name_to_id = {}
    for i, class_name in enumerate(class_names):
        class_id = i  # starts with 0
        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)

52
    out_class_names_file = osp.join(args.input_dir, 'class_names.txt')
L
LutaoChu 已提交
53 54 55 56
    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 已提交
57 58
    color_map = get_color_map_list(256)

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

            data = json.load(f)

            data_shapes = []
            if data['outputs']:
                for output in data['outputs']['object']:
                    if 'polygon' in output.keys():
                        polygon = output['polygon']
                        name = output['name']

                        # convert jingling format to labelme format
                        points = []
                        for i in range(1, int(len(polygon) / 2) + 1):
L
LutaoChu 已提交
77 78 79 80 81 82 83
                            points.append(
                                [polygon['x' + str(i)], polygon['y' + str(i)]])
                        shape = {
                            'label': name,
                            'points': points,
                            'shape_type': 'polygon'
                        }
L
LutaoChu 已提交
84 85
                        data_shapes.append(shape)

L
LutaoChu 已提交
86 87
            if 'size' not in data:
                continue
88
            data_size = data['size']
L
LutaoChu 已提交
89 90
            img_shape = (data_size['height'], data_size['width'],
                         data_size['depth'])
L
LutaoChu 已提交
91

L
LutaoChu 已提交
92
            lbl, _ = labelme.utils.shapes_to_label(
93
                img_shape=img_shape,
L
LutaoChu 已提交
94 95 96 97 98 99
                shapes=data_shapes,
                label_name_to_value=class_name_to_id,
            )

            if osp.splitext(out_png_file)[1] != '.png':
                out_png_file += '.png'
100
            # Assume label ranges [0, 255] for uint8,
L
LutaoChu 已提交
101
            if lbl.min() >= 0 and lbl.max() <= 255:
L
LutaoChu 已提交
102 103
                lbl_pil = PIL.Image.fromarray(lbl.astype(np.uint8), mode='P')
                lbl_pil.putpalette(color_map)
L
LutaoChu 已提交
104 105 106 107
                lbl_pil.save(out_png_file)
            else:
                raise ValueError(
                    '[%s] Cannot save the pixel-wise class label as PNG. '
L
LutaoChu 已提交
108
                    'Please consider using the .npy format.' % out_png_file)
L
LutaoChu 已提交
109 110 111


if __name__ == '__main__':
112 113
    args = parse_args()
    main(args)