mask2geojson.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 codecs
  15. import argparse
  16. import cv2
  17. import numpy as np
  18. import geojson
  19. from geojson import Polygon, Feature, FeatureCollection
  20. from utils import Raster, Timer
  21. def _gt_convert(x, y, geotf):
  22. x_geo = geotf[0] + x * geotf[1] + y * geotf[2]
  23. y_geo = geotf[3] + x * geotf[4] + y * geotf[5]
  24. return x_geo, y_geo
  25. @Timer
  26. def convert_data(mask_path, save_path, epsilon=0):
  27. raster = Raster(mask_path)
  28. img = raster.getArray()
  29. ext = save_path.split(".")[-1]
  30. if ext != "json" and ext != "geojson":
  31. raise ValueError("The ext of `save_path` must be `json` or `geojson`, not {}.".format(ext))
  32. geo_writer = codecs.open(save_path, "w", encoding="utf-8")
  33. clas = np.unique(img)
  34. cv2_v = (cv2.__version__.split(".")[0] == "3")
  35. feats = []
  36. if not isinstance(epsilon, (int, float)):
  37. epsilon = 0
  38. for iclas in range(1, len(clas)):
  39. tmp = np.zeros_like(img).astype("uint8")
  40. tmp[img == iclas] = 1
  41. # TODO: Detect internal and external contour
  42. results = cv2.findContours(tmp, cv2.RETR_EXTERNAL,
  43. cv2.CHAIN_APPROX_TC89_KCOS)
  44. contours = results[1] if cv2_v else results[0]
  45. # hierarchys = results[2] if cv2_v else results[1]
  46. if len(contours) == 0:
  47. continue
  48. for contour in contours:
  49. contour = cv2.approxPolyDP(contour, epsilon, True)
  50. polys = []
  51. for point in contour:
  52. x, y = point[0]
  53. xg, yg = _gt_convert(x, y, raster.geot)
  54. polys.append((xg, yg))
  55. polys.append(polys[0])
  56. feat = Feature(
  57. geometry=Polygon([polys]), properties={"class": int(iclas)})
  58. feats.append(feat)
  59. gjs = FeatureCollection(feats)
  60. geo_writer.write(geojson.dumps(gjs))
  61. geo_writer.close()
  62. parser = argparse.ArgumentParser(description="input parameters")
  63. parser.add_argument("--mask_path", type=str, required=True, \
  64. help="The path of mask tif.")
  65. parser.add_argument("--save_path", type=str, required=True, \
  66. help="The path to save the results, file suffix is `*.json/geojson`.")
  67. parser.add_argument("--epsilon", type=float, default=0, \
  68. help="The CV2 simplified parameters, `0` is the default.")
  69. if __name__ == "__main__":
  70. args = parser.parse_args()
  71. convert_data(args.mask_path, args.save_path, args.epsilon)