geojson2mask.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import os.path as osp
  16. import shutil
  17. import cv2
  18. import numpy as np
  19. import json
  20. import argparse
  21. import glob
  22. from tqdm import tqdm
  23. from PIL import Image
  24. from collections import defaultdict
  25. def _mkdir_p(path):
  26. if not osp.exists(path):
  27. os.makedirs(path)
  28. def _save_palette(label, save_path):
  29. bin_colormap = np.ones((256, 3)) * 255
  30. bin_colormap[0, :] = [0, 0, 0]
  31. bin_colormap = bin_colormap.astype(np.uint8)
  32. visualimg = Image.fromarray(label, "P")
  33. palette = bin_colormap
  34. visualimg.putpalette(palette)
  35. visualimg.save(save_path, format='PNG')
  36. def _save_mask(annotation, image_size, save_path):
  37. mask = np.zeros(image_size, dtype=np.int32)
  38. for contour_points in annotation:
  39. contour_points = np.array(contour_points).reshape((-1, 2))
  40. contour_points = np.round(contour_points).astype(np.int32)[np.newaxis, :]
  41. cv2.fillPoly(mask, contour_points, 1)
  42. _save_palette(mask.astype("uint8"), save_path)
  43. def _read_geojson(json_path):
  44. with open(json_path, "r") as f:
  45. jsoner = json.load(f)
  46. imgs = jsoner["images"]
  47. images = defaultdict(list)
  48. sizes = defaultdict(list)
  49. for img in imgs:
  50. images[img["id"]] = img["file_name"]
  51. sizes[img["file_name"]] = (img["height"], img["width"])
  52. anns = jsoner["annotations"]
  53. annotations = defaultdict(list)
  54. for ann in anns:
  55. annotations[images[ann["image_id"]]].append(ann["segmentation"])
  56. return annotations, sizes
  57. def convert_data(raw_folder, end_folder):
  58. print("-- Initializing --")
  59. img_folder = osp.join(raw_folder, "images")
  60. save_img_folder = osp.join(end_folder, "img")
  61. save_lab_folder = osp.join(end_folder, "gt")
  62. _mkdir_p(save_img_folder)
  63. _mkdir_p(save_lab_folder)
  64. names = os.listdir(img_folder)
  65. print("-- Loading annotations --")
  66. anns = {}
  67. sizes = {}
  68. jsons = glob.glob(osp.join(raw_folder, "*.json"))
  69. for json in jsons:
  70. j_ann, j_size = _read_geojson(json)
  71. anns.update(j_ann)
  72. sizes.update(j_size)
  73. print("-- Converting datas --")
  74. for k in tqdm(names):
  75. # for k in tqdm(anns.keys()):
  76. img_path = osp.join(img_folder, k)
  77. img_save_path = osp.join(save_img_folder, k)
  78. ext = "." + k.split(".")[-1]
  79. lab_save_path = osp.join(save_lab_folder, k.replace(ext, ".png"))
  80. shutil.copy(img_path, img_save_path)
  81. if k in anns.keys():
  82. _save_mask(anns[k], sizes[k], lab_save_path)
  83. else: # have not anns
  84. _save_palette(np.zeros(sizes[k], dtype="uint8"), \
  85. lab_save_path)
  86. parser = argparse.ArgumentParser(description="input parameters")
  87. parser.add_argument("--raw_folder", type=str, required=True, \
  88. help="The folder path about original data, where `images` saves the original image, `annotation.json` saves the corresponding annotation information.")
  89. parser.add_argument("--save_folder", type=str, required=True, \
  90. help="The folder path to save the results, where `img` saves the image and `gt` saves the label.")
  91. if __name__ == "__main__":
  92. args = parser.parse_args()
  93. convert_data(args.raw_folder, args.save_folder)