mask2shp.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 sys
  15. import os.path as osp
  16. sys.path.insert(0, osp.abspath("..")) # add workspace
  17. import os
  18. import numpy as np
  19. import argparse
  20. from PIL import Image
  21. from paddlers.datasets.raster import Raster
  22. try:
  23. from osgeo import gdal, ogr, osr
  24. except ImportError:
  25. import gdal
  26. import ogr
  27. import osr
  28. def _mask2tif(mask_path, tmp_path, proj, geot):
  29. mask = np.asarray(Image.open(mask_path))
  30. if len(mask.shape) == 3:
  31. mask = mask[:, :, 0]
  32. row, columns = mask.shape[:2]
  33. driver = gdal.GetDriverByName("GTiff")
  34. dst_ds = driver.Create(tmp_path, columns, row, 1, gdal.GDT_UInt16)
  35. dst_ds.SetGeoTransform(geot)
  36. dst_ds.SetProjection(proj)
  37. dst_ds.GetRasterBand(1).WriteArray(mask)
  38. dst_ds.FlushCache()
  39. return dst_ds
  40. def _polygonize_raster(mask_path, shp_save_path, proj, geot, ignore_index):
  41. tmp_path = shp_save_path.replace(".shp", ".tif")
  42. ds = _mask2tif(mask_path, tmp_path, proj, geot)
  43. srcband = ds.GetRasterBand(1)
  44. maskband = srcband.GetMaskBand()
  45. gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
  46. gdal.SetConfigOption("SHAPE_ENCODING", "UTF-8")
  47. ogr.RegisterAll()
  48. drv = ogr.GetDriverByName("ESRI Shapefile")
  49. if osp.exists(shp_save_path):
  50. os.remove(shp_save_path)
  51. dst_ds = drv.CreateDataSource(shp_save_path)
  52. prosrs = osr.SpatialReference(wkt=ds.GetProjection())
  53. dst_layer = dst_ds.CreateLayer("Building boundary", geom_type=ogr.wkbPolygon, srs=prosrs)
  54. dst_fieldname = "DN"
  55. fd = ogr.FieldDefn(dst_fieldname, ogr.OFTInteger)
  56. dst_layer.CreateField(fd)
  57. gdal.Polygonize(srcband, maskband, dst_layer, 0, [])
  58. lyr = dst_ds.GetLayer()
  59. lyr.SetAttributeFilter("DN = '{}'".format(str(ignore_index)))
  60. for holes in lyr:
  61. lyr.DeleteFeature(holes.GetFID())
  62. dst_ds.Destroy()
  63. ds = None
  64. os.remove(tmp_path)
  65. def raster2shp(srcimg_path, mask_path, save_path, ignore_index=255):
  66. src = Raster(srcimg_path)
  67. _polygonize_raster(mask_path, save_path, src.proj, src.geot, ignore_index)
  68. src = None
  69. parser = argparse.ArgumentParser(description="input parameters")
  70. parser.add_argument("--srcimg_path", type=str, required=True, \
  71. help="The path of original data with geoinfos.")
  72. parser.add_argument("--mask_path", type=str, required=True, \
  73. help="The path of mask data.")
  74. parser.add_argument("--save_path", type=str, default="output", \
  75. help="The path to save the results shapefile, `output` is the default.")
  76. parser.add_argument("--ignore_index", type=int, default=255, \
  77. help="It will not be converted to the value of SHP, `255` is the default.")
  78. if __name__ == "__main__":
  79. args = parser.parse_args()
  80. raster2shp(args.srcimg_path, args.mask_path, args.save_path, args.ignore_index)