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