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