coco2mask.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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 json
  18. import argparse
  19. from collections import defaultdict
  20. import cv2
  21. import numpy as np
  22. import glob
  23. from tqdm import tqdm
  24. from PIL import Image
  25. from utils import Timer
  26. def _mkdir_p(path):
  27. if not osp.exists(path):
  28. os.makedirs(path)
  29. def _save_palette(label, save_path):
  30. bin_colormap = np.ones((256, 3)) * 255
  31. bin_colormap[0, :] = [0, 0, 0]
  32. bin_colormap = bin_colormap.astype(np.uint8)
  33. visualimg = Image.fromarray(label, "P")
  34. palette = bin_colormap
  35. visualimg.putpalette(palette)
  36. visualimg.save(save_path, format='PNG')
  37. def _save_mask(annotation, image_size, save_path):
  38. mask = np.zeros(image_size, dtype=np.int32)
  39. for contour_points in annotation:
  40. contour_points = np.array(contour_points).reshape((-1, 2))
  41. contour_points = np.round(contour_points).astype(np.int32)[
  42. np.newaxis, :]
  43. cv2.fillPoly(mask, contour_points, 1)
  44. _save_palette(mask.astype("uint8"), save_path)
  45. def _read_geojson(json_path):
  46. with open(json_path, "r") as f:
  47. jsoner = json.load(f)
  48. imgs = jsoner["images"]
  49. images = defaultdict(list)
  50. sizes = defaultdict(list)
  51. for img in imgs:
  52. images[img["id"]] = img["file_name"]
  53. sizes[img["file_name"]] = (img["height"], img["width"])
  54. anns = jsoner["annotations"]
  55. annotations = defaultdict(list)
  56. for ann in anns:
  57. annotations[images[ann["image_id"]]].append(ann["segmentation"])
  58. return annotations, sizes
  59. @Timer
  60. def convert_data(raw_folder, end_folder):
  61. print("-- Initializing --")
  62. img_folder = osp.join(raw_folder, "images")
  63. save_img_folder = osp.join(end_folder, "img")
  64. save_lab_folder = osp.join(end_folder, "gt")
  65. _mkdir_p(save_img_folder)
  66. _mkdir_p(save_lab_folder)
  67. names = os.listdir(img_folder)
  68. print("-- Loading annotations --")
  69. anns = {}
  70. sizes = {}
  71. jsons = glob.glob(osp.join(raw_folder, "*.json"))
  72. for json in jsons:
  73. j_ann, j_size = _read_geojson(json)
  74. anns.update(j_ann)
  75. sizes.update(j_size)
  76. print("-- Converting datas --")
  77. for k in tqdm(names):
  78. # for k in tqdm(anns.keys()):
  79. img_path = osp.join(img_folder, k)
  80. img_save_path = osp.join(save_img_folder, k)
  81. ext = "." + k.split(".")[-1]
  82. lab_save_path = osp.join(save_lab_folder, k.replace(ext, ".png"))
  83. shutil.copy(img_path, img_save_path)
  84. if k in anns.keys():
  85. _save_mask(anns[k], sizes[k], lab_save_path)
  86. else: # have not anns
  87. _save_palette(np.zeros(sizes[k], dtype="uint8"), \
  88. lab_save_path)
  89. parser = argparse.ArgumentParser(description="input parameters")
  90. parser.add_argument("--raw_folder", type=str, required=True, \
  91. help="The folder path about original data, where `images` saves the original image, `annotation.json` saves the corresponding annotation information.")
  92. parser.add_argument("--save_folder", type=str, required=True, \
  93. help="The folder path to save the results, where `img` saves the image and `gt` saves the label.")
  94. if __name__ == "__main__":
  95. args = parser.parse_args()
  96. convert_data(args.raw_folder, args.save_folder)