Package osgeo :: Package utils :: Module gdal_proximity |
[hide private]
[frames] | no frames]

# Source Code for Module osgeo.utils.gdal_proximity

      1  #!/usr/bin/env python3
      2  # ******************************************************************************
      3  #  $Id$
      4  #
      5  #  Name:     gdalproximity
      6  #  Project:  GDAL Python Interface
      7  #  Purpose:  Application for computing raster proximity maps.
      8  #  Author:   Frank Warmerdam, warmerdam@pobox.com
      9  #
     10  # ******************************************************************************
     11  #  Copyright (c) 2008, Frank Warmerdam
     12  #  Copyright (c) 2009-2011, Even Rouault <even dot rouault at spatialys.com>
     13  #
     14  #  Permission is hereby granted, free of charge, to any person obtaining a
     15  #  copy of this software and associated documentation files (the "Software"),
     16  #  to deal in the Software without restriction, including without limitation
     17  #  the rights to use, copy, modify, merge, publish, distribute, sublicense,
     18  #  and/or sell copies of the Software, and to permit persons to whom the
     19  #  Software is furnished to do so, subject to the following conditions:
     20  #
     21  #  The above copyright notice and this permission notice shall be included
     22  #  in all copies or substantial portions of the Software.
     23  #
     24  #  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
     25  #  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     26  #  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
     27  #  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     28  #  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
     29  #  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
     30  #  DEALINGS IN THE SOFTWARE.
     31  # ******************************************************************************
     32
     33  import os.path
     34  import sys
     35
     36  from osgeo import gdal
     37
     38
     39 -def Usage():
     40      print("""
     41  gdal_proximity.py srcfile dstfile [-srcband n] [-dstband n]
     42                    [-of format] [-co name=value]*
     43                    [-ot Byte/UInt16/UInt32/Float32/etc]
     44                    [-values n,n,n] [-distunits PIXEL/GEO]
     45                    [-maxdist n] [-nodata n] [-use_input_nodata YES/NO]
     46                    [-fixed-buf-val n] [-q] """)
     47      sys.exit(1)
     48
     49
     50 -def DoesDriverHandleExtension(drv, ext):
     51      exts = drv.GetMetadataItem(gdal.DMD_EXTENSIONS)
     52      return exts is not None and exts.lower().find(ext.lower()) >= 0
     53
     54
     55 -def GetExtension(filename):
     56      ext = os.path.splitext(filename)[1]
     57      if ext.startswith('.'):
     58          ext = ext[1:]
     59      return ext
     60
     61
     62 -def GetOutputDriversFor(filename):
     63      drv_list = []
     64      ext = GetExtension(filename)
     65      for i in range(gdal.GetDriverCount()):
     66          drv = gdal.GetDriver(i)
     67          if (drv.GetMetadataItem(gdal.DCAP_CREATE) is not None or
     68              drv.GetMetadataItem(gdal.DCAP_CREATECOPY) is not None) and \
     69             drv.GetMetadataItem(gdal.DCAP_RASTER) is not None:
     70              if ext and DoesDriverHandleExtension(drv, ext):
     71                  drv_list.append(drv.ShortName)
     72              else:
     73                  prefix = drv.GetMetadataItem(gdal.DMD_CONNECTION_PREFIX)
     74                  if prefix is not None and filename.lower().startswith(prefix.lower()):
     75                      drv_list.append(drv.ShortName)
     76
     77      # GMT is registered before netCDF for opening reasons, but we want
     78      # netCDF to be used by default for output.
     79      if ext.lower() == 'nc' and not drv_list and \
     80         drv_list[0].upper() == 'GMT' and drv_list[1].upper() == 'NETCDF':
     81          drv_list = ['NETCDF', 'GMT']
     82
     83      return drv_list
     84
     85
     86 -def GetOutputDriverFor(filename):
     87      drv_list = GetOutputDriversFor(filename)
     88      ext = GetExtension(filename)
     89      if not drv_list:
     90          if not ext:
     91              return 'GTiff'
     92          else:
     93              raise Exception("Cannot guess driver for %s" % filename)
     94      elif len(drv_list) > 1:
     95          print("Several drivers matching %s extension. Using %s" % (ext if ext else '', drv_list[0]))
     96      return drv_list[0]
     97
     98
     99 -def main(argv):
    100      frmt = None
    101      creation_options = []
    102      options = []
    103      src_filename = None
    104      src_band_n = 1
    105      dst_filename = None
    106      dst_band_n = 1
    107      creation_type = 'Float32'
    108      quiet_flag = 0
    109
    110      gdal.AllRegister()
    111      argv = gdal.GeneralCmdLineProcessor(argv)
    112      if argv is None:
    113          sys.exit(0)
    114
    115      # Parse command line arguments.
    116      i = 1
    117      while i < len(argv):
    118          arg = argv[i]
    119
    120          if arg == '-of' or arg == '-f':
    121              i = i + 1
    122              frmt = argv[i]
    123
    124          elif arg == '-co':
    125              i = i + 1
    126              creation_options.append(argv[i])
    127
    128          elif arg == '-ot':
    129              i = i + 1
    130              creation_type = argv[i]
    131
    132          elif arg == '-maxdist':
    133              i = i + 1
    134              options.append('MAXDIST=' + argv[i])
    135
    136          elif arg == '-values':
    137              i = i + 1
    138              options.append('VALUES=' + argv[i])
    139
    140          elif arg == '-distunits':
    141              i = i + 1
    142              options.append('DISTUNITS=' + argv[i])
    143
    144          elif arg == '-nodata':
    145              i = i + 1
    146              options.append('NODATA=' + argv[i])
    147
    148          elif arg == '-use_input_nodata':
    149              i = i + 1
    150              options.append('USE_INPUT_NODATA=' + argv[i])
    151
    152          elif arg == '-fixed-buf-val':
    153              i = i + 1
    154              options.append('FIXED_BUF_VAL=' + argv[i])
    155
    156          elif arg == '-srcband':
    157              i = i + 1
    158              src_band_n = int(argv[i])
    159
    160          elif arg == '-dstband':
    161              i = i + 1
    162              dst_band_n = int(argv[i])
    163
    164          elif arg == '-q' or arg == '-quiet':
    165              quiet_flag = 1
    166
    167          elif src_filename is None:
    168              src_filename = argv[i]
    169
    170          elif dst_filename is None:
    171              dst_filename = argv[i]
    172
    173          else:
    174              Usage()
    175
    176          i = i + 1
    177
    178      if src_filename is None or dst_filename is None:
    179          Usage()
    180
    181      # =============================================================================
    182      #    Open source file
    183      # =============================================================================
    184
    185      src_ds = gdal.Open(src_filename)
    186
    187      if src_ds is None:
    188          print('Unable to open %s' % src_filename)
    189          sys.exit(1)
    190
    191      srcband = src_ds.GetRasterBand(src_band_n)
    192
    193      # =============================================================================
    194      #       Try opening the destination file as an existing file.
    195      # =============================================================================
    196
    197      try:
    198          driver = gdal.IdentifyDriver(dst_filename)
    199          if driver is not None:
    200              dst_ds = gdal.Open(dst_filename, gdal.GA_Update)
    201              dstband = dst_ds.GetRasterBand(dst_band_n)
    202          else:
    203              dst_ds = None
    204      except:
    205          dst_ds = None
    206
    207      # =============================================================================
    208      #     Create output file.
    209      # =============================================================================
    210      if dst_ds is None:
    211          if frmt is None:
    212              frmt = GetOutputDriverFor(dst_filename)
    213
    214          drv = gdal.GetDriverByName(frmt)
    215          dst_ds = drv.Create(dst_filename,
    216                              src_ds.RasterXSize, src_ds.RasterYSize, 1,
    217                              gdal.GetDataTypeByName(creation_type), creation_options)
    218
    219          dst_ds.SetGeoTransform(src_ds.GetGeoTransform())
    220          dst_ds.SetProjection(src_ds.GetProjectionRef())
    221
    222          dstband = dst_ds.GetRasterBand(1)
    223
    224      # =============================================================================
    225      #    Invoke algorithm.
    226      # =============================================================================
    227
    228      if quiet_flag:
    229          prog_func = None
    230      else:
    231          prog_func = gdal.TermProgress_nocb
    232
    233      gdal.ComputeProximity(srcband, dstband, options,
    234                            callback=prog_func)
    235
    236      srcband = None
    237      dstband = None
    238      src_ds = None
    239      dst_ds = None
    240
    241
    242  if __name__ == '__main__':
    243      sys.exit(main(sys.argv))
    244