We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
LabelMe标注好图片之后，使用labelme2seg无法生成真值图片
我使用LabelMe标注好图片之后，使用labelme2seg生成真值图片，运行labelme2seg的时候报错，报错信息如下：
class_names: ('_background_', 'steel')
Saved class_names: D:\2\class_names.txt
Generating dataset from: D:\2\2020_5_15_13_19_46_995.json
Traceback (most recent call last):
  File "D:\PaddleSeg\pdseg\tools\labelme2seg.py", line 90, in <module>
    main(args)
  File "D:\PaddleSeg\pdseg\tools\labelme2seg.py", line 78, in main
    if lbl.min() >= 0 and lbl.max() <= 255:
AttributeError: 'tuple' object has no attribute 'min'

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pdseg/tools/labelme2seg.py`
Content:
```
1 # coding: utf8
2 # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 #    http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 
16 from __future__ import print_function
17 
18 import argparse
19 import glob
20 import json
21 import os
22 import os.path as osp
23 
24 import numpy as np
25 import PIL.Image
26 import labelme
27 
28 from gray2pseudo_color import get_color_map_list
29 
30 
31 def parse_args():
32     parser = argparse.ArgumentParser(
33         formatter_class=argparse.ArgumentDefaultsHelpFormatter)
34     parser.add_argument('input_dir', help='input annotated directory')
35     return parser.parse_args()
36 
37 
38 def main(args):
39     output_dir = osp.join(args.input_dir, 'annotations')
40     if not osp.exists(output_dir):
41         os.makedirs(output_dir)
42         print('Creating annotations directory:', output_dir)
43 
44     # get the all class names for the given dataset
45     class_names = ['_background_']
46     for label_file in glob.glob(osp.join(args.input_dir, '*.json')):
47         with open(label_file) as f:
48             data = json.load(f)
49             for shape in data['shapes']:
50                 label = shape['label']
51                 cls_name = label
52                 if not cls_name in class_names:
53                     class_names.append(cls_name)
54 
55     class_name_to_id = {}
56     for i, class_name in enumerate(class_names):
57         class_id = i  # starts with 0
58         class_name_to_id[class_name] = class_id
59         if class_id == 0:
60             assert class_name == '_background_'
61     class_names = tuple(class_names)
62     print('class_names:', class_names)
63 
64     out_class_names_file = osp.join(args.input_dir, 'class_names.txt')
65     with open(out_class_names_file, 'w') as f:
66         f.writelines('\n'.join(class_names))
67     print('Saved class_names:', out_class_names_file)
68 
69     color_map = get_color_map_list(256)
70 
71     for label_file in glob.glob(osp.join(args.input_dir, '*.json')):
72         print('Generating dataset from:', label_file)
73         with open(label_file) as f:
74             base = osp.splitext(osp.basename(label_file))[0]
75             out_png_file = osp.join(output_dir, base + '.png')
76 
77             data = json.load(f)
78 
79             img_file = osp.join(osp.dirname(label_file), data['imagePath'])
80             img = np.asarray(PIL.Image.open(img_file))
81 
82             lbl = labelme.utils.shapes_to_label(
83                 img_shape=img.shape,
84                 shapes=data['shapes'],
85                 label_name_to_value=class_name_to_id,
86             )
87 
88             if osp.splitext(out_png_file)[1] != '.png':
89                 out_png_file += '.png'
90             # Assume label ranges [0, 255] for uint8,
91             if lbl.min() >= 0 and lbl.max() <= 255:
92                 lbl_pil = PIL.Image.fromarray(lbl.astype(np.uint8), mode='P')
93                 lbl_pil.putpalette(color_map)
94                 lbl_pil.save(out_png_file)
95             else:
96                 raise ValueError(
97                     '[%s] Cannot save the pixel-wise class label as PNG. '
98                     'Please consider using the .npy format.' % out_png_file)
99 
100 
101 if __name__ == '__main__':
102     args = parse_args()
103     main(args)
104
```

Path: `pdseg/tools/jingling2seg.py`
Content:
```
1 # coding: utf8
2 # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 #    http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 
16 from __future__ import print_function
17 
18 import argparse
19 import glob
20 import json
21 import os
22 import os.path as osp
23 
24 import numpy as np
25 import PIL.Image
26 import labelme
27 
28 from gray2pseudo_color import get_color_map_list
29 
30 
31 def parse_args():
32     parser = argparse.ArgumentParser(
33         formatter_class=argparse.ArgumentDefaultsHelpFormatter)
34     parser.add_argument('input_dir', help='input annotated directory')
35     return parser.parse_args()
36 
37 
38 def main(args):
39     output_dir = osp.join(args.input_dir, 'annotations')
40     if not osp.exists(output_dir):
41         os.makedirs(output_dir)
42         print('Creating annotations directory:', output_dir)
43 
44     # get the all class names for the given dataset
45     class_names = ['_background_']
46     for label_file in glob.glob(osp.join(args.input_dir, '*.json')):
47         with open(label_file) as f:
48             data = json.load(f)
49             if data['outputs']:
50                 for output in data['outputs']['object']:
51                     name = output['name']
52                     cls_name = name
53                     if not cls_name in class_names:
54                         class_names.append(cls_name)
55 
56     class_name_to_id = {}
57     for i, class_name in enumerate(class_names):
58         class_id = i  # starts with 0
59         class_name_to_id[class_name] = class_id
60         if class_id == 0:
61             assert class_name == '_background_'
62     class_names = tuple(class_names)
63     print('class_names:', class_names)
64 
65     out_class_names_file = osp.join(args.input_dir, 'class_names.txt')
66     with open(out_class_names_file, 'w') as f:
67         f.writelines('\n'.join(class_names))
68     print('Saved class_names:', out_class_names_file)
69 
70     color_map = get_color_map_list(256)
71 
72     for label_file in glob.glob(osp.join(args.input_dir, '*.json')):
73         print('Generating dataset from:', label_file)
74         with open(label_file) as f:
75             base = osp.splitext(osp.basename(label_file))[0]
76             out_png_file = osp.join(output_dir, base + '.png')
77 
78             data = json.load(f)
79 
80             data_shapes = []
81             if data['outputs']:
82                 for output in data['outputs']['object']:
83                     if 'polygon' in output.keys():
84                         polygon = output['polygon']
85                         name = output['name']
86 
87                         # convert jingling format to labelme format
88                         points = []
89                         for i in range(1, int(len(polygon) / 2) + 1):
90                             points.append(
91                                 [polygon['x' + str(i)], polygon['y' + str(i)]])
92                         shape = {
93                             'label': name,
94                             'points': points,
95                             'shape_type': 'polygon'
96                         }
97                         data_shapes.append(shape)
98 
99             if 'size' not in data:
100                 continue
101             data_size = data['size']
102             img_shape = (data_size['height'], data_size['width'],
103                          data_size['depth'])
104 
105             lbl = labelme.utils.shapes_to_label(
106                 img_shape=img_shape,
107                 shapes=data_shapes,
108                 label_name_to_value=class_name_to_id,
109             )
110 
111             if osp.splitext(out_png_file)[1] != '.png':
112                 out_png_file += '.png'
113             # Assume label ranges [0, 255] for uint8,
114             if lbl.min() >= 0 and lbl.max() <= 255:
115                 lbl_pil = PIL.Image.fromarray(lbl.astype(np.uint8), mode='P')
116                 lbl_pil.putpalette(color_map)
117                 lbl_pil.save(out_png_file)
118             else:
119                 raise ValueError(
120                     '[%s] Cannot save the pixel-wise class label as PNG. '
121                     'Please consider using the .npy format.' % out_png_file)
122 
123 
124 if __name__ == '__main__':
125     args = parse_args()
126     main(args)
127
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/pdseg/tools/jingling2seg.py b/pdseg/tools/jingling2seg.py
--- a/pdseg/tools/jingling2seg.py
+++ b/pdseg/tools/jingling2seg.py
@@ -20,12 +20,11 @@
 import json
 import os
 import os.path as osp
-
 import numpy as np
 import PIL.Image
-import labelme
 
 from gray2pseudo_color import get_color_map_list
+from labelme2seg import shape2label
 
 
 def parse_args():
@@ -102,10 +101,10 @@
             img_shape = (data_size['height'], data_size['width'],
                          data_size['depth'])
 
-            lbl = labelme.utils.shapes_to_label(
-                img_shape=img_shape,
+            lbl = shape2label(
+                img_size=img_shape,
                 shapes=data_shapes,
-                label_name_to_value=class_name_to_id,
+                class_name_mapping=class_name_to_id,
             )
 
             if osp.splitext(out_png_file)[1] != '.png':
diff --git a/pdseg/tools/labelme2seg.py b/pdseg/tools/labelme2seg.py
--- a/pdseg/tools/labelme2seg.py
+++ b/pdseg/tools/labelme2seg.py
@@ -17,13 +17,14 @@
 
 import argparse
 import glob
+import math
 import json
 import os
 import os.path as osp
-
 import numpy as np
 import PIL.Image
-import labelme
+import PIL.ImageDraw
+import cv2
 
 from gray2pseudo_color import get_color_map_list
 
@@ -77,12 +78,12 @@
             data = json.load(f)
 
             img_file = osp.join(osp.dirname(label_file), data['imagePath'])
-            img = np.asarray(PIL.Image.open(img_file))
+            img = np.asarray(cv2.imread(img_file))
 
-            lbl = labelme.utils.shapes_to_label(
-                img_shape=img.shape,
+            lbl = shape2label(
+                img_size=img.shape,
                 shapes=data['shapes'],
-                label_name_to_value=class_name_to_id,
+                class_name_mapping=class_name_to_id,
             )
 
             if osp.splitext(out_png_file)[1] != '.png':
@@ -98,6 +99,27 @@
                     'Please consider using the .npy format.' % out_png_file)
 
 
+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
+
+
 if __name__ == '__main__':
     args = parse_args()
     main(args)

{"golden_diff": "diff --git a/pdseg/tools/jingling2seg.py b/pdseg/tools/jingling2seg.py\n--- a/pdseg/tools/jingling2seg.py\n+++ b/pdseg/tools/jingling2seg.py\n@@ -20,12 +20,11 @@\n import json\n import os\n import os.path as osp\n-\n import numpy as np\n import PIL.Image\n-import labelme\n \n from gray2pseudo_color import get_color_map_list\n+from labelme2seg import shape2label\n \n \n def parse_args():\n@@ -102,10 +101,10 @@\n             img_shape = (data_size['height'], data_size['width'],\n                          data_size['depth'])\n \n-            lbl = labelme.utils.shapes_to_label(\n-                img_shape=img_shape,\n+            lbl = shape2label(\n+                img_size=img_shape,\n                 shapes=data_shapes,\n-                label_name_to_value=class_name_to_id,\n+                class_name_mapping=class_name_to_id,\n             )\n \n             if osp.splitext(out_png_file)[1] != '.png':\ndiff --git a/pdseg/tools/labelme2seg.py b/pdseg/tools/labelme2seg.py\n--- a/pdseg/tools/labelme2seg.py\n+++ b/pdseg/tools/labelme2seg.py\n@@ -17,13 +17,14 @@\n \n import argparse\n import glob\n+import math\n import json\n import os\n import os.path as osp\n-\n import numpy as np\n import PIL.Image\n-import labelme\n+import PIL.ImageDraw\n+import cv2\n \n from gray2pseudo_color import get_color_map_list\n \n@@ -77,12 +78,12 @@\n             data = json.load(f)\n \n             img_file = osp.join(osp.dirname(label_file), data['imagePath'])\n-            img = np.asarray(PIL.Image.open(img_file))\n+            img = np.asarray(cv2.imread(img_file))\n \n-            lbl = labelme.utils.shapes_to_label(\n-                img_shape=img.shape,\n+            lbl = shape2label(\n+                img_size=img.shape,\n                 shapes=data['shapes'],\n-                label_name_to_value=class_name_to_id,\n+                class_name_mapping=class_name_to_id,\n             )\n \n             if osp.splitext(out_png_file)[1] != '.png':\n@@ -98,6 +99,27 @@\n                     'Please consider using the .npy format.' % out_png_file)\n \n \n+def shape2mask(img_size, points):\n+    label_mask = PIL.Image.fromarray(np.zeros(img_size[:2], dtype=np.uint8))\n+    image_draw = PIL.ImageDraw.Draw(label_mask)\n+    points_list = [tuple(point) for point in points]\n+    assert len(points_list) > 2, 'Polygon must have points more than 2'\n+    image_draw.polygon(xy=points_list, outline=1, fill=1)\n+    return np.array(label_mask, dtype=bool)\n+\n+\n+def shape2label(img_size, shapes, class_name_mapping):\n+    label = np.zeros(img_size[:2], dtype=np.int32)\n+    for shape in shapes:\n+        points = shape['points']\n+        class_name = shape['label']\n+        shape_type = shape.get('shape_type', None)\n+        class_id = class_name_mapping[class_name]\n+        label_mask = shape2mask(img_size[:2], points)\n+        label[label_mask] = class_id\n+    return label\n+\n+\n if __name__ == '__main__':\n     args = parse_args()\n     main(args)\n", "issue": "LabelMe\u6807\u6ce8\u597d\u56fe\u7247\u4e4b\u540e\uff0c\u4f7f\u7528labelme2seg\u65e0\u6cd5\u751f\u6210\u771f\u503c\u56fe\u7247\n\u6211\u4f7f\u7528LabelMe\u6807\u6ce8\u597d\u56fe\u7247\u4e4b\u540e\uff0c\u4f7f\u7528labelme2seg\u751f\u6210\u771f\u503c\u56fe\u7247\uff0c\u8fd0\u884clabelme2seg\u7684\u65f6\u5019\u62a5\u9519\uff0c\u62a5\u9519\u4fe1\u606f\u5982\u4e0b\uff1a\r\nclass_names: ('_background_', 'steel')\r\nSaved class_names: D:\\2\\class_names.txt\r\nGenerating dataset from: D:\\2\\2020_5_15_13_19_46_995.json\r\nTraceback (most recent call last):\r\n  File \"D:\\PaddleSeg\\pdseg\\tools\\labelme2seg.py\", line 90, in <module>\r\n    main(args)\r\n  File \"D:\\PaddleSeg\\pdseg\\tools\\labelme2seg.py\", line 78, in main\r\n    if lbl.min() >= 0 and lbl.max() <= 255:\r\nAttributeError: 'tuple' object has no attribute 'min'\n", "before_files": [{"content": "# coding: utf8\n# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport argparse\nimport glob\nimport json\nimport os\nimport os.path as osp\n\nimport numpy as np\nimport PIL.Image\nimport labelme\n\nfrom gray2pseudo_color import get_color_map_list\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser(\n        formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n    parser.add_argument('input_dir', help='input annotated directory')\n    return parser.parse_args()\n\n\ndef main(args):\n    output_dir = osp.join(args.input_dir, 'annotations')\n    if not osp.exists(output_dir):\n        os.makedirs(output_dir)\n        print('Creating annotations directory:', output_dir)\n\n    # get the all class names for the given dataset\n    class_names = ['_background_']\n    for label_file in glob.glob(osp.join(args.input_dir, '*.json')):\n        with open(label_file) as f:\n            data = json.load(f)\n            for shape in data['shapes']:\n                label = shape['label']\n                cls_name = label\n                if not cls_name in class_names:\n                    class_names.append(cls_name)\n\n    class_name_to_id = {}\n    for i, class_name in enumerate(class_names):\n        class_id = i  # starts with 0\n        class_name_to_id[class_name] = class_id\n        if class_id == 0:\n            assert class_name == '_background_'\n    class_names = tuple(class_names)\n    print('class_names:', class_names)\n\n    out_class_names_file = osp.join(args.input_dir, 'class_names.txt')\n    with open(out_class_names_file, 'w') as f:\n        f.writelines('\\n'.join(class_names))\n    print('Saved class_names:', out_class_names_file)\n\n    color_map = get_color_map_list(256)\n\n    for label_file in glob.glob(osp.join(args.input_dir, '*.json')):\n        print('Generating dataset from:', label_file)\n        with open(label_file) as f:\n            base = osp.splitext(osp.basename(label_file))[0]\n            out_png_file = osp.join(output_dir, base + '.png')\n\n            data = json.load(f)\n\n            img_file = osp.join(osp.dirname(label_file), data['imagePath'])\n            img = np.asarray(PIL.Image.open(img_file))\n\n            lbl = labelme.utils.shapes_to_label(\n                img_shape=img.shape,\n                shapes=data['shapes'],\n                label_name_to_value=class_name_to_id,\n            )\n\n            if osp.splitext(out_png_file)[1] != '.png':\n                out_png_file += '.png'\n            # Assume label ranges [0, 255] for uint8,\n            if lbl.min() >= 0 and lbl.max() <= 255:\n                lbl_pil = PIL.Image.fromarray(lbl.astype(np.uint8), mode='P')\n                lbl_pil.putpalette(color_map)\n                lbl_pil.save(out_png_file)\n            else:\n                raise ValueError(\n                    '[%s] Cannot save the pixel-wise class label as PNG. '\n                    'Please consider using the .npy format.' % out_png_file)\n\n\nif __name__ == '__main__':\n    args = parse_args()\n    main(args)\n", "path": "pdseg/tools/labelme2seg.py"}, {"content": "# coding: utf8\n# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport argparse\nimport glob\nimport json\nimport os\nimport os.path as osp\n\nimport numpy as np\nimport PIL.Image\nimport labelme\n\nfrom gray2pseudo_color import get_color_map_list\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser(\n        formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n    parser.add_argument('input_dir', help='input annotated directory')\n    return parser.parse_args()\n\n\ndef main(args):\n    output_dir = osp.join(args.input_dir, 'annotations')\n    if not osp.exists(output_dir):\n        os.makedirs(output_dir)\n        print('Creating annotations directory:', output_dir)\n\n    # get the all class names for the given dataset\n    class_names = ['_background_']\n    for label_file in glob.glob(osp.join(args.input_dir, '*.json')):\n        with open(label_file) as f:\n            data = json.load(f)\n            if data['outputs']:\n                for output in data['outputs']['object']:\n                    name = output['name']\n                    cls_name = name\n                    if not cls_name in class_names:\n                        class_names.append(cls_name)\n\n    class_name_to_id = {}\n    for i, class_name in enumerate(class_names):\n        class_id = i  # starts with 0\n        class_name_to_id[class_name] = class_id\n        if class_id == 0:\n            assert class_name == '_background_'\n    class_names = tuple(class_names)\n    print('class_names:', class_names)\n\n    out_class_names_file = osp.join(args.input_dir, 'class_names.txt')\n    with open(out_class_names_file, 'w') as f:\n        f.writelines('\\n'.join(class_names))\n    print('Saved class_names:', out_class_names_file)\n\n    color_map = get_color_map_list(256)\n\n    for label_file in glob.glob(osp.join(args.input_dir, '*.json')):\n        print('Generating dataset from:', label_file)\n        with open(label_file) as f:\n            base = osp.splitext(osp.basename(label_file))[0]\n            out_png_file = osp.join(output_dir, base + '.png')\n\n            data = json.load(f)\n\n            data_shapes = []\n            if data['outputs']:\n                for output in data['outputs']['object']:\n                    if 'polygon' in output.keys():\n                        polygon = output['polygon']\n                        name = output['name']\n\n                        # convert jingling format to labelme format\n                        points = []\n                        for i in range(1, int(len(polygon) / 2) + 1):\n                            points.append(\n                                [polygon['x' + str(i)], polygon['y' + str(i)]])\n                        shape = {\n                            'label': name,\n                            'points': points,\n                            'shape_type': 'polygon'\n                        }\n                        data_shapes.append(shape)\n\n            if 'size' not in data:\n                continue\n            data_size = data['size']\n            img_shape = (data_size['height'], data_size['width'],\n                         data_size['depth'])\n\n            lbl = labelme.utils.shapes_to_label(\n                img_shape=img_shape,\n                shapes=data_shapes,\n                label_name_to_value=class_name_to_id,\n            )\n\n            if osp.splitext(out_png_file)[1] != '.png':\n                out_png_file += '.png'\n            # Assume label ranges [0, 255] for uint8,\n            if lbl.min() >= 0 and lbl.max() <= 255:\n                lbl_pil = PIL.Image.fromarray(lbl.astype(np.uint8), mode='P')\n                lbl_pil.putpalette(color_map)\n                lbl_pil.save(out_png_file)\n            else:\n                raise ValueError(\n                    '[%s] Cannot save the pixel-wise class label as PNG. '\n                    'Please consider using the .npy format.' % out_png_file)\n\n\nif __name__ == '__main__':\n    args = parse_args()\n    main(args)\n", "path": "pdseg/tools/jingling2seg.py"}], "after_files": [{"content": "# coding: utf8\n# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport argparse\nimport glob\nimport math\nimport json\nimport os\nimport os.path as osp\nimport numpy as np\nimport PIL.Image\nimport PIL.ImageDraw\nimport cv2\n\nfrom gray2pseudo_color import get_color_map_list\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser(\n        formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n    parser.add_argument('input_dir', help='input annotated directory')\n    return parser.parse_args()\n\n\ndef main(args):\n    output_dir = osp.join(args.input_dir, 'annotations')\n    if not osp.exists(output_dir):\n        os.makedirs(output_dir)\n        print('Creating annotations directory:', output_dir)\n\n    # get the all class names for the given dataset\n    class_names = ['_background_']\n    for label_file in glob.glob(osp.join(args.input_dir, '*.json')):\n        with open(label_file) as f:\n            data = json.load(f)\n            for shape in data['shapes']:\n                label = shape['label']\n                cls_name = label\n                if not cls_name in class_names:\n                    class_names.append(cls_name)\n\n    class_name_to_id = {}\n    for i, class_name in enumerate(class_names):\n        class_id = i  # starts with 0\n        class_name_to_id[class_name] = class_id\n        if class_id == 0:\n            assert class_name == '_background_'\n    class_names = tuple(class_names)\n    print('class_names:', class_names)\n\n    out_class_names_file = osp.join(args.input_dir, 'class_names.txt')\n    with open(out_class_names_file, 'w') as f:\n        f.writelines('\\n'.join(class_names))\n    print('Saved class_names:', out_class_names_file)\n\n    color_map = get_color_map_list(256)\n\n    for label_file in glob.glob(osp.join(args.input_dir, '*.json')):\n        print('Generating dataset from:', label_file)\n        with open(label_file) as f:\n            base = osp.splitext(osp.basename(label_file))[0]\n            out_png_file = osp.join(output_dir, base + '.png')\n\n            data = json.load(f)\n\n            img_file = osp.join(osp.dirname(label_file), data['imagePath'])\n            img = np.asarray(cv2.imread(img_file))\n\n            lbl = shape2label(\n                img_size=img.shape,\n                shapes=data['shapes'],\n                class_name_mapping=class_name_to_id,\n            )\n\n            if osp.splitext(out_png_file)[1] != '.png':\n                out_png_file += '.png'\n            # Assume label ranges [0, 255] for uint8,\n            if lbl.min() >= 0 and lbl.max() <= 255:\n                lbl_pil = PIL.Image.fromarray(lbl.astype(np.uint8), mode='P')\n                lbl_pil.putpalette(color_map)\n                lbl_pil.save(out_png_file)\n            else:\n                raise ValueError(\n                    '[%s] Cannot save the pixel-wise class label as PNG. '\n                    'Please consider using the .npy format.' % out_png_file)\n\n\ndef shape2mask(img_size, points):\n    label_mask = PIL.Image.fromarray(np.zeros(img_size[:2], dtype=np.uint8))\n    image_draw = PIL.ImageDraw.Draw(label_mask)\n    points_list = [tuple(point) for point in points]\n    assert len(points_list) > 2, 'Polygon must have points more than 2'\n    image_draw.polygon(xy=points_list, outline=1, fill=1)\n    return np.array(label_mask, dtype=bool)\n\n\ndef shape2label(img_size, shapes, class_name_mapping):\n    label = np.zeros(img_size[:2], dtype=np.int32)\n    for shape in shapes:\n        points = shape['points']\n        class_name = shape['label']\n        shape_type = shape.get('shape_type', None)\n        class_id = class_name_mapping[class_name]\n        label_mask = shape2mask(img_size[:2], points)\n        label[label_mask] = class_id\n    return label\n\n\nif __name__ == '__main__':\n    args = parse_args()\n    main(args)\n", "path": "pdseg/tools/labelme2seg.py"}, {"content": "# coding: utf8\n# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport argparse\nimport glob\nimport json\nimport os\nimport os.path as osp\nimport numpy as np\nimport PIL.Image\n\nfrom gray2pseudo_color import get_color_map_list\nfrom labelme2seg import shape2label\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser(\n        formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n    parser.add_argument('input_dir', help='input annotated directory')\n    return parser.parse_args()\n\n\ndef main(args):\n    output_dir = osp.join(args.input_dir, 'annotations')\n    if not osp.exists(output_dir):\n        os.makedirs(output_dir)\n        print('Creating annotations directory:', output_dir)\n\n    # get the all class names for the given dataset\n    class_names = ['_background_']\n    for label_file in glob.glob(osp.join(args.input_dir, '*.json')):\n        with open(label_file) as f:\n            data = json.load(f)\n            if data['outputs']:\n                for output in data['outputs']['object']:\n                    name = output['name']\n                    cls_name = name\n                    if not cls_name in class_names:\n                        class_names.append(cls_name)\n\n    class_name_to_id = {}\n    for i, class_name in enumerate(class_names):\n        class_id = i  # starts with 0\n        class_name_to_id[class_name] = class_id\n        if class_id == 0:\n            assert class_name == '_background_'\n    class_names = tuple(class_names)\n    print('class_names:', class_names)\n\n    out_class_names_file = osp.join(args.input_dir, 'class_names.txt')\n    with open(out_class_names_file, 'w') as f:\n        f.writelines('\\n'.join(class_names))\n    print('Saved class_names:', out_class_names_file)\n\n    color_map = get_color_map_list(256)\n\n    for label_file in glob.glob(osp.join(args.input_dir, '*.json')):\n        print('Generating dataset from:', label_file)\n        with open(label_file) as f:\n            base = osp.splitext(osp.basename(label_file))[0]\n            out_png_file = osp.join(output_dir, base + '.png')\n\n            data = json.load(f)\n\n            data_shapes = []\n            if data['outputs']:\n                for output in data['outputs']['object']:\n                    if 'polygon' in output.keys():\n                        polygon = output['polygon']\n                        name = output['name']\n\n                        # convert jingling format to labelme format\n                        points = []\n                        for i in range(1, int(len(polygon) / 2) + 1):\n                            points.append(\n                                [polygon['x' + str(i)], polygon['y' + str(i)]])\n                        shape = {\n                            'label': name,\n                            'points': points,\n                            'shape_type': 'polygon'\n                        }\n                        data_shapes.append(shape)\n\n            if 'size' not in data:\n                continue\n            data_size = data['size']\n            img_shape = (data_size['height'], data_size['width'],\n                         data_size['depth'])\n\n            lbl = shape2label(\n                img_size=img_shape,\n                shapes=data_shapes,\n                class_name_mapping=class_name_to_id,\n            )\n\n            if osp.splitext(out_png_file)[1] != '.png':\n                out_png_file += '.png'\n            # Assume label ranges [0, 255] for uint8,\n            if lbl.min() >= 0 and lbl.max() <= 255:\n                lbl_pil = PIL.Image.fromarray(lbl.astype(np.uint8), mode='P')\n                lbl_pil.putpalette(color_map)\n                lbl_pil.save(out_png_file)\n            else:\n                raise ValueError(\n                    '[%s] Cannot save the pixel-wise class label as PNG. '\n                    'Please consider using the .npy format.' % out_png_file)\n\n\nif __name__ == '__main__':\n    args = parse_args()\n    main(args)\n", "path": "pdseg/tools/jingling2seg.py"}]}