mask2shape.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #!/usr/bin/env python
  2. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import os
  16. import os.path as osp
  17. import argparse
  18. import paddlers
  19. import numpy as np
  20. from PIL import Image
  21. try:
  22. from osgeo import gdal, ogr, osr
  23. except ImportError:
  24. import gdal
  25. import ogr
  26. import osr
  27. from utils import Raster, save_geotiff, time_it
  28. def _mask2tif(mask_path, tmp_path, proj, geot):
  29. dst_ds = save_geotiff(
  30. np.asarray(Image.open(mask_path)), tmp_path, proj, geot,
  31. gdal.GDT_UInt16, False)
  32. return dst_ds
  33. def _polygonize_raster(mask_path, vec_save_path, proj, geot, ignore_index, ext):
  34. if proj is None or geot is None:
  35. tmp_path = None
  36. ds = gdal.Open(mask_path)
  37. else:
  38. tmp_path = vec_save_path.replace("." + ext, ".tif")
  39. ds = _mask2tif(mask_path, tmp_path, proj, geot)
  40. srcband = ds.GetRasterBand(1)
  41. maskband = srcband.GetMaskBand()
  42. gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
  43. gdal.SetConfigOption("SHAPE_ENCODING", "UTF-8")
  44. ogr.RegisterAll()
  45. drv = ogr.GetDriverByName("ESRI Shapefile" if ext == "shp" else "GeoJSON")
  46. if osp.exists(vec_save_path):
  47. os.remove(vec_save_path)
  48. dst_ds = drv.CreateDataSource(vec_save_path)
  49. prosrs = osr.SpatialReference(wkt=ds.GetProjection())
  50. dst_layer = dst_ds.CreateLayer(
  51. "POLYGON", geom_type=ogr.wkbPolygon, srs=prosrs)
  52. dst_fieldname = "CLAS"
  53. fd = ogr.FieldDefn(dst_fieldname, ogr.OFTInteger)
  54. dst_layer.CreateField(fd)
  55. gdal.Polygonize(srcband, maskband, dst_layer, 0, [])
  56. # TODO: temporary: delete ignored values
  57. dst_ds.Destroy()
  58. ds = None
  59. vec_ds = drv.Open(vec_save_path, 1)
  60. lyr = vec_ds.GetLayer()
  61. lyr.SetAttributeFilter("{} = '{}'".format(dst_fieldname, str(ignore_index)))
  62. for holes in lyr:
  63. lyr.DeleteFeature(holes.GetFID())
  64. vec_ds.Destroy()
  65. if tmp_path is not None:
  66. os.remove(tmp_path)
  67. @time_it
  68. def mask2shape(src_img_path, mask_path, save_path, ignore_index=255):
  69. vec_ext = save_path.split(".")[-1].lower()
  70. if vec_ext not in ["json", "geojson", "shp"]:
  71. raise ValueError(
  72. "The extension of `save_path` must be 'json/geojson' or 'shp', not {}.".
  73. format(vec_ext))
  74. ras_ext = src_img_path.split(".")[-1].lower()
  75. if osp.exists(
  76. src_img_path) and ras_ext in ["tif", "tiff", "geotiff", "img"]:
  77. src = Raster(src_img_path)
  78. _polygonize_raster(mask_path, save_path, src.proj, src.geot,
  79. ignore_index, vec_ext)
  80. src = None
  81. else:
  82. _polygonize_raster(mask_path, save_path, None, None, ignore_index,
  83. vec_ext)
  84. if __name__ == "__main__":
  85. parser = argparse.ArgumentParser()
  86. parser.add_argument("--mask_path", type=str, required=True, \
  87. help="Path of mask data.")
  88. parser.add_argument("--save_path", type=str, required=True, \
  89. help="Path to save the shape file (the extension is .json/geojson or .shp).")
  90. parser.add_argument("--src_img_path", type=str, default="", \
  91. help="Path of original data with geoinfo. Default to empty.")
  92. parser.add_argument("--ignore_index", type=int, default=255, \
  93. help="The ignored index will not be converted to a value in the shape file. Default value is 255.")
  94. args = parser.parse_args()
  95. mask2shape(args.src_img_path, args.mask_path, args.save_path,
  96. args.ignore_index)