mask2shp.py 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 numpy as np
  17. import argparse
  18. from PIL import Image
  19. from utils import Raster, Timer
  20. try:
  21. from osgeo import gdal, ogr, osr
  22. except ImportError:
  23. import gdal
  24. import ogr
  25. import osr
  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)