geojson2mask.py 2.7 KB

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