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 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, Timer
  26. def _mask2tif(mask_path, tmp_path, proj, geot):
  27. mask = np.asarray(Image.open(mask_path))
  28. if len(mask.shape) == 3:
  29. mask = mask[:, :, 0]
  30. row, columns = mask.shape[:2]
  31. driver = gdal.GetDriverByName("GTiff")
  32. dst_ds = driver.Create(tmp_path, columns, row, 1, gdal.GDT_UInt16)
  33. dst_ds.SetGeoTransform(geot)
  34. dst_ds.SetProjection(proj)
  35. dst_ds.GetRasterBand(1).WriteArray(mask)
  36. dst_ds.FlushCache()
  37. return dst_ds
  38. def _polygonize_raster(mask_path, shp_save_path, proj, geot, ignore_index):
  39. tmp_path = shp_save_path.replace(".shp", ".tif")
  40. ds = _mask2tif(mask_path, tmp_path, proj, geot)
  41. srcband = ds.GetRasterBand(1)
  42. maskband = srcband.GetMaskBand()
  43. gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
  44. gdal.SetConfigOption("SHAPE_ENCODING", "UTF-8")
  45. ogr.RegisterAll()
  46. drv = ogr.GetDriverByName("ESRI Shapefile")
  47. if osp.exists(shp_save_path):
  48. os.remove(shp_save_path)
  49. dst_ds = drv.CreateDataSource(shp_save_path)
  50. prosrs = osr.SpatialReference(wkt=ds.GetProjection())
  51. dst_layer = dst_ds.CreateLayer(
  52. "Building boundary", geom_type=ogr.wkbPolygon, srs=prosrs)
  53. dst_fieldname = "DN"
  54. fd = ogr.FieldDefn(dst_fieldname, ogr.OFTInteger)
  55. dst_layer.CreateField(fd)
  56. gdal.Polygonize(srcband, maskband, dst_layer, 0, [])
  57. lyr = dst_ds.GetLayer()
  58. lyr.SetAttributeFilter("DN = '{}'".format(str(ignore_index)))
  59. for holes in lyr:
  60. lyr.DeleteFeature(holes.GetFID())
  61. dst_ds.Destroy()
  62. ds = None
  63. os.remove(tmp_path)
  64. @Timer
  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,
  81. args.ignore_index)