raster2geotiff.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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,
  26. b)).tolist() # Solve a quadratic equation
  27. @time_it
  28. # TODO: update for vector2raster
  29. def convert_data(image_path, geojson_path):
  30. raster = Raster(image_path)
  31. tmp_img = np.zeros((raster.height, raster.width), dtype=np.int32)
  32. # vector to EPSG from raster
  33. temp_geojson_path = translate_vector(geojson_path, raster.proj)
  34. geo_reader = codecs.open(temp_geojson_path, "r", encoding="utf-8")
  35. feats = geojson.loads(geo_reader.read())["features"] # All image patches
  36. geo_reader.close()
  37. for feat in tqdm(feats):
  38. geo = feat["geometry"]
  39. if geo["type"] == "Polygon":
  40. geo_points = geo["coordinates"][0]
  41. elif geo["type"] == "MultiPolygon":
  42. geo_points = geo["coordinates"][0][0]
  43. else:
  44. raise TypeError(
  45. "Geometry type must be 'Polygon' or 'MultiPolygon', not {}.".
  46. format(geo["type"]))
  47. xy_points = np.array([
  48. _gt_convert(point[0], point[1], raster.geot) for point in geo_points
  49. ]).astype(np.int32)
  50. # TODO: Label category
  51. cv2.fillPoly(tmp_img, [xy_points], 1) # Fill with polygons
  52. ext = "." + geojson_path.split(".")[-1]
  53. save_geotiff(tmp_img,
  54. geojson_path.replace(ext, ".tif"), raster.proj, raster.geot)
  55. os.remove(temp_geojson_path)
  56. parser = argparse.ArgumentParser()
  57. parser.add_argument("--raster_path", type=str, required=True, \
  58. help="Path of original raster image.")
  59. parser.add_argument("--geotiff_path", type=str, required=True, \
  60. help="Path to store the geotiff file (the coordinate system is WGS84).")
  61. if __name__ == "__main__":
  62. args = parser.parse_args()
  63. convert_data(args.raster_path, args.geotiff_path)