geojson2mask.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 cv2
  16. import numpy as np
  17. import argparse
  18. import geojson
  19. from tqdm import tqdm
  20. from utils import Raster, save_mask_geotiff, Timer
  21. def _gt_convert(x_geo, y_geo, geotf):
  22. a = np.array([[geotf[1], geotf[2]], [geotf[4], geotf[5]]])
  23. b = np.array([x_geo - geotf[0], y_geo - geotf[3]])
  24. return np.round(np.linalg.solve(a, b)).tolist() # 解一元二次方程
  25. @Timer
  26. def convert_data(image_path, geojson_path):
  27. raster = Raster(image_path)
  28. tmp_img = np.zeros((raster.height, raster.width), dtype=np.int32)
  29. geo_reader = codecs.open(geojson_path, "r", encoding="utf-8")
  30. feats = geojson.loads(geo_reader.read())["features"] # 所有图像块
  31. for feat in tqdm(feats):
  32. geo = feat["geometry"]
  33. if geo["type"] == "Polygon": # 多边形
  34. geo_points = geo["coordinates"][0]
  35. elif geo["type"] == "MultiPolygon": # 多面
  36. geo_points = geo["coordinates"][0][0]
  37. else:
  38. raise TypeError("Geometry type must be `Polygon` or `MultiPolygon`, not {}.".format(geo["type"]))
  39. xy_points = np.array([
  40. _gt_convert(point[0], point[1], raster.geot)
  41. for point in geo_points
  42. ]).astype(np.int32)
  43. # TODO: Label category
  44. cv2.fillPoly(tmp_img, [xy_points], 1) # 多边形填充
  45. ext = "." + geojson_path.split(".")[-1]
  46. save_mask_geotiff(tmp_img, geojson_path.replace(ext, ".tif"), raster.proj, raster.geot)
  47. parser = argparse.ArgumentParser(description="input parameters")
  48. parser.add_argument("--image_path", type=str, required=True, \
  49. help="The path of original image.")
  50. parser.add_argument("--geojson_path", type=str, required=True, \
  51. help="The path of geojson.")
  52. if __name__ == "__main__":
  53. args = parser.parse_args()
  54. convert_data(args.image_path, args.geojson_path)