labelme2cityscape.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import argparse
  17. import glob
  18. import json
  19. import os
  20. import os.path as osp
  21. import numpy as np
  22. class MyEncoder(json.JSONEncoder):
  23. def default(self, obj):
  24. if isinstance(obj, np.integer):
  25. return int(obj)
  26. elif isinstance(obj, np.floating):
  27. return float(obj)
  28. elif isinstance(obj, np.ndarray):
  29. return obj.tolist()
  30. else:
  31. return super(MyEncoder, self).default(obj)
  32. def deal_json(json_file):
  33. data_cs = {}
  34. objects = []
  35. num = -1
  36. num = num + 1
  37. if not json_file.endswith('.json'):
  38. print('Cannot generating dataset from:', json_file)
  39. return None
  40. with open(json_file) as f:
  41. print('Generating dataset from:', json_file)
  42. data = json.load(f)
  43. data_cs['imgHeight'] = data['imageHeight']
  44. data_cs['imgWidth'] = data['imageWidth']
  45. for shapes in data['shapes']:
  46. obj = {}
  47. label = shapes['label']
  48. obj['label'] = label
  49. points = shapes['points']
  50. p_type = shapes['shape_type']
  51. if p_type == 'polygon':
  52. obj['polygon'] = points
  53. objects.append(obj)
  54. data_cs['objects'] = objects
  55. return data_cs
  56. def main():
  57. parser = argparse.ArgumentParser(
  58. formatter_class=argparse.ArgumentDefaultsHelpFormatter, )
  59. parser.add_argument('--json_input_dir', help='input annotated directory')
  60. parser.add_argument(
  61. '--output_dir',
  62. help='output dataset directory', )
  63. args = parser.parse_args()
  64. try:
  65. assert os.path.exists(args.json_input_dir)
  66. except AssertionError as e:
  67. print('The json folder does not exist!')
  68. os._exit(0)
  69. # Deal with the json files.
  70. total_num = len(glob.glob(osp.join(args.json_input_dir, '*.json')))
  71. for json_name in os.listdir(args.json_input_dir):
  72. data_cs = deal_json(osp.join(args.json_input_dir, json_name))
  73. if data_cs is None:
  74. continue
  75. json.dump(
  76. data_cs,
  77. open(osp.join(args.output_dir, json_name), 'w'),
  78. indent=4,
  79. cls=MyEncoder, )
  80. if __name__ == '__main__':
  81. main()