vector.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. # reference: https://zhuanlan.zhihu.com/p/378918221
  15. try:
  16. from osgeo import gdal, ogr, osr
  17. except:
  18. import gdal
  19. import ogr
  20. import osr
  21. def translate_vector(geojson_path: str,
  22. wo_wkt: str,
  23. g_type: str="POLYGON",
  24. dim: str="XY") -> str:
  25. ogr.RegisterAll()
  26. gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
  27. data = ogr.Open(geojson_path)
  28. layer = data.GetLayer()
  29. spatial = layer.GetSpatialRef()
  30. layerName = layer.GetName()
  31. data.Destroy()
  32. dstSRS = osr.SpatialReference()
  33. dstSRS.ImportFromWkt(wo_wkt)
  34. ext = "." + geojson_path.split(".")[-1]
  35. save_path = geojson_path.replace(ext, ("_tmp" + ext))
  36. options = gdal.VectorTranslateOptions(
  37. srcSRS=spatial,
  38. dstSRS=dstSRS,
  39. reproject=True,
  40. layerName=layerName,
  41. geometryType=g_type,
  42. dim=dim)
  43. gdal.VectorTranslate(save_path, srcDS=geojson_path, options=options)
  44. return save_path