labelme2seg.py 4.3 KB
Newer Older
W
wuyefeilin 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# coding: utf8
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
W
wuzewu 已提交
15 16 17 18 19

from __future__ import print_function

import argparse
import glob
L
LutaoChu 已提交
20
import math
W
wuzewu 已提交
21 22 23 24 25
import json
import os
import os.path as osp
import numpy as np
import PIL.Image
L
LutaoChu 已提交
26 27
import PIL.ImageDraw
import cv2
W
wuzewu 已提交
28

29
from gray2pseudo_color import get_color_map_list
L
LutaoChu 已提交
30

W
wuzewu 已提交
31

32
def parse_args():
W
wuzewu 已提交
33
    parser = argparse.ArgumentParser(
L
LutaoChu 已提交
34 35
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('input_dir', help='input annotated directory')
36 37 38 39 40 41 42 43
    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 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57

    # 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):
58
        class_id = i  # starts with 0
W
wuzewu 已提交
59 60 61 62 63 64
        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)

65
    out_class_names_file = osp.join(args.input_dir, 'class_names.txt')
W
wuzewu 已提交
66 67 68 69
    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 已提交
70 71
    color_map = get_color_map_list(256)

W
wuzewu 已提交
72 73 74 75
    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]
L
LutaoChu 已提交
76
            out_png_file = osp.join(output_dir, base + '.png')
W
wuzewu 已提交
77 78 79 80

            data = json.load(f)

            img_file = osp.join(osp.dirname(label_file), data['imagePath'])
L
LutaoChu 已提交
81
            img = np.asarray(cv2.imread(img_file))
W
wuzewu 已提交
82

L
LutaoChu 已提交
83 84
            lbl = shape2label(
                img_size=img.shape,
W
wuzewu 已提交
85
                shapes=data['shapes'],
L
LutaoChu 已提交
86
                class_name_mapping=class_name_to_id,
W
wuzewu 已提交
87 88 89 90
            )

            if osp.splitext(out_png_file)[1] != '.png':
                out_png_file += '.png'
91
            # Assume label ranges [0, 255] for uint8,
W
wuzewu 已提交
92
            if lbl.min() >= 0 and lbl.max() <= 255:
L
LutaoChu 已提交
93 94
                lbl_pil = PIL.Image.fromarray(lbl.astype(np.uint8), mode='P')
                lbl_pil.putpalette(color_map)
W
wuzewu 已提交
95 96 97 98
                lbl_pil.save(out_png_file)
            else:
                raise ValueError(
                    '[%s] Cannot save the pixel-wise class label as PNG. '
L
LutaoChu 已提交
99
                    'Please consider using the .npy format.' % out_png_file)
W
wuzewu 已提交
100

101

L
LutaoChu 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
def shape2mask(img_size, points):
    label_mask = PIL.Image.fromarray(np.zeros(img_size[:2], dtype=np.uint8))
    image_draw = PIL.ImageDraw.Draw(label_mask)
    points_list = [tuple(point) for point in points]
    assert len(points_list) > 2, 'Polygon must have points more than 2'
    image_draw.polygon(xy=points_list, outline=1, fill=1)
    return np.array(label_mask, dtype=bool)


def shape2label(img_size, shapes, class_name_mapping):
    label = np.zeros(img_size[:2], dtype=np.int32)
    for shape in shapes:
        points = shape['points']
        class_name = shape['label']
        shape_type = shape.get('shape_type', None)
        class_id = class_name_mapping[class_name]
        label_mask = shape2mask(img_size[:2], points)
        label[label_mask] = class_id
    return label


W
wuzewu 已提交
123
if __name__ == '__main__':
124 125
    args = parse_args()
    main(args)