r.fillnulls.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. #!/usr/bin/env python
  2. #
  3. ############################################################################
  4. #
  5. # MODULE: r.fillnulls
  6. # AUTHOR(S): Markus Neteler <neteler itc it>
  7. # Updated to GRASS 5.7 by Michael Barton
  8. # Updated to GRASS 6.0 by Markus Neteler
  9. # Ring improvements by Hamish Bowman
  10. # Converted to Python by Glynn Clements
  11. # PURPOSE: fills NULL (no data areas) in raster maps
  12. # The script respects a user mask (MASK) if present.
  13. #
  14. # COPYRIGHT: (C) 2001,2004-2005,2008 by the GRASS Development Team
  15. #
  16. # This program is free software under the GNU General Public
  17. # License (>=v2). Read the file COPYING that comes with GRASS
  18. # for details.
  19. #
  20. #############################################################################
  21. #%Module
  22. #% description: Fills no-data areas in raster maps using v.surf.rst splines interpolation
  23. #% keywords: raster
  24. #% keywords: elevation
  25. #% keywords: interpolation
  26. #%End
  27. #%option
  28. #% key: input
  29. #% gisprompt: old,cell,raster
  30. #% type: string
  31. #% description: Raster map in which to fill nulls
  32. #% required : yes
  33. #%end
  34. #%option
  35. #% key: output
  36. #% gisprompt: new,cell,raster
  37. #% type: string
  38. #% description: Output raster map with nulls filled by interpolation from surrounding values
  39. #% required : yes
  40. #%end
  41. #%option
  42. #% key: tension
  43. #% type: double
  44. #% description: Spline tension parameter
  45. #% required : no
  46. #% answer : 40.
  47. #%end
  48. #%option
  49. #% key: smooth
  50. #% type: double
  51. #% description: Spline smoothing parameter
  52. #% required : no
  53. #% answer : 0.1
  54. #%end
  55. import sys
  56. import os
  57. import atexit
  58. import grass.script as grass
  59. vecttmp = None
  60. tmp1 = None
  61. usermask = None
  62. mapset = None
  63. # what to do in case of user break:
  64. def cleanup():
  65. #delete internal mask and any TMP files:
  66. if tmp1:
  67. rasts = [tmp1 + ext for ext in ['', '.buf', '_filled']]
  68. grass.run_command('g.remove', flags = 'f', rast = rasts)
  69. if vecttmp:
  70. grass.run_command('g.remove', flags = 'f', vect = vecttmp)
  71. grass.run_command('g.remove', rast = 'MASK')
  72. if usermask and mapset:
  73. if grass.find_file(usermask, mapset = mapset)['file']:
  74. grass.run_command('g.rename', rast = (usermask, 'MASK'))
  75. def main():
  76. global vecttmp, tmp1, usermask, mapset
  77. input = options['input']
  78. output = options['output']
  79. tension = options['tension']
  80. smooth = options['smooth']
  81. mapset = grass.gisenv()['MAPSET']
  82. unique = str(os.getpid())
  83. #check if input file exists
  84. if not grass.find_file(input)['file']:
  85. grass.fatal(_("<%s> does not exist.") % input)
  86. # check if a MASK is already present:
  87. usermask = "usermask_mask." + unique
  88. if grass.find_file('MASK', mapset = mapset)['file']:
  89. grass.message(_("A user raster mask (MASK) is present. Saving it..."))
  90. grass.run_command('g.rename', rast = ('MASK',usermask))
  91. #make a mask of NULL cells
  92. tmp1 = "r_fillnulls_" + unique
  93. # idea: filter all NULLS and grow that area(s) by 3 pixel, then
  94. # interpolate from these surrounding 3 pixel edge
  95. grass.message(_("Locating and isolating NULL areas..."))
  96. #creating 0/1 map:
  97. grass.mapcalc("$tmp1 = if(isnull($input),1,null())",
  98. tmp1 = tmp1, input = input)
  99. #generate a ring:
  100. # the buffer is set to three times the map resolution so you get nominally
  101. # three points around the edge. This way you interpolate into the hole with
  102. # a trained slope & curvature at the edges, otherwise you just get a flat plane.
  103. # With just a single row of cells around the hole you often get gaps
  104. # around the edges when distance > mean (.5 of the time? diagonals? worse
  105. # when ewres!=nsres).
  106. reg = grass.region()
  107. res = (float(reg['nsres']) + float(reg['ewres'])) * 3 / 2
  108. if grass.run_command('r.buffer', input = tmp1, distances = res, out = tmp1 + '.buf') != 0:
  109. grass.fatal(_("abandoned. Removing temporary map, restoring user mask if needed:"))
  110. grass.mapcalc("MASK=if($tmp1.buf==2,1,null())", tmp1 = tmp1)
  111. # now we only see the outlines of the NULL areas if looking at INPUT.
  112. # Use this outline (raster border) for interpolating the fill data:
  113. vecttmp = "vecttmp_fillnulls_" + unique
  114. grass.message(_("Creating interpolation points..."))
  115. if grass.run_command('r.to.vect', input = input, output = vecttmp, feature = 'point'):
  116. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  117. # count number of points to control segmax parameter for interpolation:
  118. pointsnumber = grass.vector_info_topo(map = vecttmp)['points']
  119. grass.message(_("Interpolating %d points") % pointsnumber)
  120. if pointsnumber < 2:
  121. grass.fatal(_("Not sufficient points to interpolate. Maybe no hole(s) to fill in the current map region?"))
  122. grass.message(_("Note: The following warnings may be ignored."))
  123. # remove internal MASK first -- WHY???? MN 10/2005
  124. grass.run_command('g.remove', rast = 'MASK')
  125. if grass.find_file(usermask, mapset = mapset)['file']:
  126. grass.message(_("Using user mask while interpolating"))
  127. maskmap = usermask
  128. else:
  129. maskmap = None
  130. segmax = 600
  131. if pointsnumber > segmax:
  132. grass.message(_("Using segmentation for interpolation..."))
  133. segmax = None
  134. else:
  135. grass.message(_("Using no segmentation for interpolation as not needed..."))
  136. grass.run_command('v.surf.rst', input = vecttmp, elev = tmp1 + '_filled',
  137. zcol = 'value', tension = tension, smooth = smooth,
  138. maskmap = maskmap, segmax = segmax)
  139. grass.message(_("Note: Above warnings may be ignored."))
  140. # restoring user's mask, if present:
  141. if grass.find_file(usermask, mapset = mapset)['file']:
  142. grass.message(_("Restoring user mask (MASK)..."))
  143. grass.run_command('g.rename', rast = (usermask, 'MASK'))
  144. # patch orig and fill map
  145. grass.message(_("Patching fill data into NULL areas..."))
  146. # we can use --o here as g.parser already checks on startup
  147. grass.run_command('r.patch', input = (input,tmp1 + '_filled'), output = output, overwrite = True)
  148. grass.message(_("Filled raster map is: %s") % output)
  149. # write cmd history:
  150. grass.raster_history(output)
  151. grass.message(_("Done."))
  152. if __name__ == "__main__":
  153. options, flags = grass.parser()
  154. atexit.register(cleanup)
  155. main()