raster2vector.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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 os.path as osp
  16. import argparse
  17. import numpy as np
  18. from PIL import Image
  19. try:
  20. from osgeo import gdal, ogr, osr
  21. except ImportError:
  22. import gdal
  23. import ogr
  24. import osr
  25. from utils import Raster, save_geotiff, time_it
  26. def _mask2tif(mask_path, tmp_path, proj, geot):
  27. dst_ds = save_geotiff(
  28. np.asarray(Image.open(mask_path)), tmp_path, proj, geot,
  29. gdal.GDT_UInt16, False)
  30. return dst_ds
  31. def _polygonize_raster(mask_path, vec_save_path, proj, geot, ignore_index, ext):
  32. if proj is None or geot is None:
  33. tmp_path = None
  34. ds = gdal.Open(mask_path)
  35. else:
  36. tmp_path = vec_save_path.replace("." + ext, ".tif")
  37. ds = _mask2tif(mask_path, tmp_path, proj, geot)
  38. srcband = ds.GetRasterBand(1)
  39. maskband = srcband.GetMaskBand()
  40. gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
  41. gdal.SetConfigOption("SHAPE_ENCODING", "UTF-8")
  42. ogr.RegisterAll()
  43. drv = ogr.GetDriverByName("ESRI Shapefile" if ext == "shp" else "GeoJSON")
  44. if osp.exists(vec_save_path):
  45. os.remove(vec_save_path)
  46. dst_ds = drv.CreateDataSource(vec_save_path)
  47. prosrs = osr.SpatialReference(wkt=ds.GetProjection())
  48. dst_layer = dst_ds.CreateLayer(
  49. "POLYGON", geom_type=ogr.wkbPolygon, srs=prosrs)
  50. dst_fieldname = "CLAS"
  51. fd = ogr.FieldDefn(dst_fieldname, ogr.OFTInteger)
  52. dst_layer.CreateField(fd)
  53. gdal.Polygonize(srcband, maskband, dst_layer, 0, [])
  54. # TODO: temporary: delete ignored values
  55. dst_ds.Destroy()
  56. ds = None
  57. vec_ds = drv.Open(vec_save_path, 1)
  58. lyr = vec_ds.GetLayer()
  59. lyr.SetAttributeFilter("{} = '{}'".format(dst_fieldname, str(ignore_index)))
  60. for holes in lyr:
  61. lyr.DeleteFeature(holes.GetFID())
  62. vec_ds.Destroy()
  63. if tmp_path is not None:
  64. os.remove(tmp_path)
  65. @time_it
  66. def raster2vector(srcimg_path, mask_path, save_path, ignore_index=255):
  67. vec_ext = save_path.split(".")[-1].lower()
  68. if vec_ext not in ["json", "geojson", "shp"]:
  69. raise ValueError(
  70. "The ext of `save_path` must be `json/geojson` or `shp`, not {}.".
  71. format(vec_ext))
  72. ras_ext = srcimg_path.split(".")[-1].lower()
  73. if osp.exists(srcimg_path) and ras_ext in ["tif", "tiff", "geotiff", "img"]:
  74. src = Raster(srcimg_path)
  75. _polygonize_raster(mask_path, save_path, src.proj, src.geot,
  76. ignore_index, vec_ext)
  77. src = None
  78. else:
  79. _polygonize_raster(mask_path, save_path, None, None, ignore_index,
  80. vec_ext)
  81. parser = argparse.ArgumentParser()
  82. parser.add_argument("--mask_path", type=str, required=True, \
  83. help="Path of mask data.")
  84. parser.add_argument("--save_path", type=str, required=True, \
  85. help="Path to save the shape file (the file suffix is `*.json/geojson` or `*.shp`).")
  86. parser.add_argument("--srcimg_path", type=str, default="", \
  87. help="Path of original data with geoinfo. Default to empty.")
  88. parser.add_argument("--ignore_index", type=int, default=255, \
  89. help="The ignored index will not be converted to a value in the shape file. Default value is `255`.")
  90. if __name__ == "__main__":
  91. args = parser.parse_args()
  92. raster2vector(args.srcimg_path, args.mask_path, args.save_path,
  93. args.ignore_index)