coco2mask.py 3.8 KB

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