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 time_it
  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. @time_it
  60. def convert_data(raw_dir, end_dir):
  61. print("-- Initializing --")
  62. img_dir = osp.join(raw_dir, "images")
  63. save_img_dir = osp.join(end_dir, "img")
  64. save_lab_dir = osp.join(end_dir, "gt")
  65. _mkdir_p(save_img_dir)
  66. _mkdir_p(save_lab_dir)
  67. names = os.listdir(img_dir)
  68. print("-- Loading annotations --")
  69. anns = {}
  70. sizes = {}
  71. jsons = glob.glob(osp.join(raw_dir, "*.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 data --")
  77. for k in tqdm(names):
  78. # for k in tqdm(anns.keys()):
  79. img_path = osp.join(img_dir, k)
  80. img_save_path = osp.join(save_img_dir, k)
  81. ext = "." + k.split(".")[-1]
  82. lab_save_path = osp.join(save_lab_dir, 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()
  90. parser.add_argument("--raw_dir", type=str, required=True, \
  91. help="Directory that contains original data, where `images` stores the original image and `annotation.json` stores the corresponding annotation information.")
  92. parser.add_argument("--save_dir", type=str, required=True, \
  93. help="Directory to save the results, where `img` stores the image and `gt` stores the label.")
  94. if __name__ == "__main__":
  95. args = parser.parse_args()
  96. convert_data(args.raw_dir, args.save_dir)