[GRASS-SVN] r70723 - in grass-addons/grass7/imagery: . i.variance

svn_grass at osgeo.org svn_grass at osgeo.org
Fri Mar 3 08:31:14 PST 2017


Author: mlennert
Date: 2017-03-03 08:31:14 -0800 (Fri, 03 Mar 2017)
New Revision: 70723

Added:
   grass-addons/grass7/imagery/i.variance/
   grass-addons/grass7/imagery/i.variance/Makefile
   grass-addons/grass7/imagery/i.variance/i.variance.html
   grass-addons/grass7/imagery/i.variance/i.variance.py
   grass-addons/grass7/imagery/i.variance/i_variance_plot.png
Log:
i.variance: new addon to calculate scale of spatial variability in images

Added: grass-addons/grass7/imagery/i.variance/Makefile
===================================================================
--- grass-addons/grass7/imagery/i.variance/Makefile	                        (rev 0)
+++ grass-addons/grass7/imagery/i.variance/Makefile	2017-03-03 16:31:14 UTC (rev 70723)
@@ -0,0 +1,7 @@
+MODULE_TOPDIR = ../..
+
+PGM = i.variance
+
+include $(MODULE_TOPDIR)/include/Make/Script.make
+
+default: script


Property changes on: grass-addons/grass7/imagery/i.variance/Makefile
___________________________________________________________________
Added: svn:mime-type
   + text/x-makefile
Added: svn:eol-style
   + native

Added: grass-addons/grass7/imagery/i.variance/i.variance.html
===================================================================
--- grass-addons/grass7/imagery/i.variance/i.variance.html	                        (rev 0)
+++ grass-addons/grass7/imagery/i.variance/i.variance.html	2017-03-03 16:31:14 UTC (rev 70723)
@@ -0,0 +1,99 @@
+<h2>DESCRIPTION</h2>
+
+<p>Following the Woodcock and Strahler (1987), <em>i.variance</em> resamples 
+a raster <em>input</em> layer (normally a remotely sensed image) to 
+successively decreasing resolutions and calculates the mean local variance of
+the entire image at each resolution. Local variance is defined as the variance
+in a 3x3 window.
+
+<p>
+The modules starts at the current computing region resolution and then decreases
+the resolution (increases the pixel size) by <em>step</em> until it
+reaches the maximum size of pixels (aka minimum resolution) determined by
+the <em>max_size</em> parameter, or when the number of total pixels falls below
+<em>min_cells</em>. If both are given, <em>min_cells</em> takes precedence.
+
+<p>
+Resampling to lower resolution uses the average of higher resolution pixels.
+
+<p>
+By default, the module prints a comma separated list to stdout containing each
+resolution that represents a local maximum of variance (higher variance than
+the resolution before and after in the iterations) as well as the difference in
+variance with the neighbor with most similar variance.
+
+<p>
+In addition, the user can choose to output the results in the form of a graph 
+plotting variance against resolution (<em>plot_output</em>) either to a file
+by giving a file name (its extension determines the output format) or to
+the screen using '-'. The entire data of variance depending on resolution can
+also be saved in a csv file using <em>csv_output</em>.
+
+<h2>NOTES</h2>
+
+The aim of this module is to provide diagnostics to the user about the size of
+detectable "objects" in an image. This can provide helpful input to modules
+that take a window size or desired object size as input, such as, for example,
+<a href="r.texture.html">r.texture</a> and 
+<a href="i.segment.html">i.segment</a>.
+
+<p>
+As Woodcock and Strahler (1980) write: "The reasoning
+behind this measure is as follows. If the spatial resolution is 
+considerably finer than the objects in the scene, most of the measurements in 
+the image will be highly correlated with their neighbors and a measure of 
+local variance will be low. If the objects approximate the size of the
+resolution cells, then the likelihood of neighbors being similar decreases and 
+the local variance rises. As the size of the resolution cells increase and many
+objects are found in a single resolution cell, the local variance decreases."
+
+
+<h2>EXAMPLE</h2>
+
+<div class="code"><pre> 
+g.region rast=ortho_2001_t792_1m
+i.variance ortho_2001_t792_1m max_size=50 plot_output=i_variance_plot.png
+<br>
+resolution,min_diff
+1,106.964
+9,0.120383
+11,0.199415
+14,0.332985
+19,0.132208
+21,0.318132
+25,0.0357517
+28,2.2714
+30,1.7073
+32,1.65568
+37,1.7664
+42,1.12972
+45,1.25903
+48,4.41572
+50,0.154997
+</pre></div>
+
+
+<center>
+	        <img src="i_variance_plot.png" border="1"><br>
+		 Plot of variance against resolution
+</center>
+
+<h2>REFERENCES</h2>
+
+Woodcock, C.E., Strahler, A.H., 1987. The factor of scale in remote sensing. 
+	Remote Sensing of Environment 21, 311–332. 
+	http://doi.org/10.1016/0034-4257(87)90015-0
+
+<h2>SEE ALSO</h2>
+
+<a href="r.resamp.stats.html">r.resamp.stats</a>,<br>
+<a href="r.neighbors.html">r.neighbors</a>,<br>
+<a href="r.univar.html">r.univar</a>,<br>
+<a href="i.segment.html">i.segment</a>,<br>
+<a href="r.texture.html">r.texture</a>
+
+<h2>AUTHOR</h2> 
+
+Moritz Lennert
+
+<p><i>Last changed: $Date$</i>


Property changes on: grass-addons/grass7/imagery/i.variance/i.variance.html
___________________________________________________________________
Added: svn:mime-type
   + text/html
Added: svn:keywords
   + Author Date Id
Added: svn:eol-style
   + native

Added: grass-addons/grass7/imagery/i.variance/i.variance.py
===================================================================
--- grass-addons/grass7/imagery/i.variance/i.variance.py	                        (rev 0)
+++ grass-addons/grass7/imagery/i.variance/i.variance.py	2017-03-03 16:31:14 UTC (rev 70723)
@@ -0,0 +1,221 @@
+#!/usr/bin/env python
+
+############################################################################
+#
+# MODULE:	i.variance
+# AUTHOR(S):	Moritz Lennert
+#
+# PURPOSE:	Calculate variation of variance by variation of resolution
+# COPYRIGHT:	(C) 1997-2016 by the GRASS Development Team
+#
+#		This program is free software under the GNU General Public
+#		License (>=v2). Read the file COPYING that comes with GRASS
+#		for details.
+#
+#############################################################################
+# Curtis E. Woodcock, Alan H. Strahler, The factor of scale in remote sensing,
+# Remote Sensing of Environment, Volume 21, Issue 3, April 1987, Pages 311-332,
+# ISSN 0034-4257, http://dx.doi.org/10.1016/0034-4257(87)90015-0.
+#
+#############################################################################
+
+#%Module
+#% description: Analyses variation of variance with variation of resolution
+#% keyword: imagery
+#% keyword: variance
+#% keyword: resolution
+#%end
+#
+#%option G_OPT_R_INPUT
+#% description: Raster band  on which to perform analysis of variation of variance
+#%end
+#
+#%option G_OPT_F_OUTPUT
+#% key: csv_output
+#% label: Name for output file
+#% required: no
+#%end
+#
+#%option G_OPT_F_OUTPUT
+#% key: plot_output
+#% label: Name for graphic output file for plot (extension decides format, - for screen)
+#% required: no
+#%end
+#
+#%option
+#% key: min_cells
+#% type: integer
+#% description: Minimum number of cells at which to stop
+#% required: no
+#% multiple: no
+#%end
+#
+#%option
+#% key: max_size
+#% type: double
+#% description: Maximum pixel size (= minimum resolution) to analyse  
+#% required: no
+#% multiple: no
+#%end
+#
+#%option
+#% key: step
+#% type: double
+#% description: Step of resolution variation
+#% required: yes
+#% answer: 1
+#% multiple: no
+#%end
+#
+#%rules
+#% required: min_cells,max_size
+#%end
+
+import sys
+import os
+import atexit
+from math import sqrt
+import matplotlib.pyplot as plt
+import grass.script as gscript
+
+def cleanup():
+    if gscript.find_file(temp_resamp_map, element='raster')['name']:
+        gscript.run_command('g.remove', flags='f', type='raster',
+                          name=temp_resamp_map, quiet=True)
+    if gscript.find_file(temp_variance_map, element='raster')['name']:
+        gscript.run_command('g.remove', flags='f', type='raster',
+                          name=temp_variance_map, quiet=True)
+
+def FindMaxima(numbers):
+  maxima = []
+  differences = []
+  length = len(numbers)
+  if length >= 2:
+    if numbers[0] > numbers[1]:
+      maxima.append(0)
+      differences.append(numbers[0] - numbers[1])
+       
+    if length > 3:
+      for i in range(1, length-1):     
+        if numbers[i] > numbers[i-1] and numbers[i] > numbers[i+1]:
+          maxima.append(i)
+          differences.append(min(numbers[i] - numbers[i-1], numbers[i] - numbers[i+1]))
+
+    if numbers[length-1] > numbers[length-2]:    
+      maxima.append(length-1)        
+      differences.append(numbers[length-1] - numbers[length-2])
+
+  return maxima, differences
+
+def main():
+    input = options['input']
+    output = None
+    if options['csv_output']:
+        output = options['csv_output']
+    plot_output = None
+    if options['plot_output']:
+        plot_output = options['plot_output']
+    min_cells = False
+    if options['min_cells']:
+        min_cells = int(options['min_cells'])
+    target_res = None
+    if options['max_size']:
+    	target_res = float(options['max_size'])
+    step = float(options['step'])
+
+    global temp_resamp_map, temp_variance_map
+    temp_resamp_map = "temp_resamp_map_%d" % os.getpid()
+    temp_variance_map = "temp_variance_map_%d" % os.getpid()
+    resolutions = []
+    variances = []
+
+    region = gscript.parse_command('g.region', flags='g')
+    cells = int(region['cells'])
+    res = (float(region['nsres']) + float(region['ewres'])) / 2 
+    north = float(region['n'])
+    south = float(region['s'])
+    west = float(region['w'])
+    east = float(region['e'])
+
+    if res % 1 == 0 and step % 1 == 0:
+	template_string = "%d,%f\n"
+    else:
+	template_string = "%f,%f\n"
+
+    if min_cells:
+        target_res_cells = int(sqrt(((east - west) * (north - south)) / min_cells))
+        if target_res > target_res_cells:
+            target_res = target_res_cells
+            gscript.message(_("Max resolution leads to less cells than defined by 'min_cells' (%d)." % min_cells)) 
+            gscript.message(_("Max resolution reduced to %d" % target_res))
+
+    nb_iterations = target_res - res / step
+    if nb_iterations < 3:
+        message = _("Less than 3 iterations. Cannot determine maxima.\n")
+        message += _("Please increase max_size or reduce min_cells.")
+        gscript.fatal(_(message))
+
+    gscript.use_temp_region()
+
+    gscript.message(_("Calculating variance at different resolutions"))
+    while res <= target_res:
+	gscript.percent(res, target_res, step)
+	gscript.run_command('r.resamp.stats',
+			    input=input,
+			    output=temp_resamp_map,
+			    method='average',
+			    quiet=True,
+			    overwrite=True)
+	gscript.run_command('r.neighbors',
+			    input=temp_resamp_map,
+			    method='variance',
+			    output=temp_variance_map,
+			    quiet=True,
+			    overwrite=True)
+	varianceinfo = gscript.parse_command('r.univar',
+					     map_=temp_variance_map,
+					     flags='g',
+					     quiet=True)
+        resolutions.append(res)
+	variances.append(float(varianceinfo['mean']))
+	res += step
+        region = gscript.parse_command('g.region',
+			    res=res,
+			    n=north,
+			    s=south,
+			    w=west,
+			    e=east,
+			    flags='ag')
+	cells = int(region['cells'])
+
+    indices, differences = FindMaxima(variances)
+    max_resolutions = [resolutions[x] for x in indices]
+    gscript.message(_("resolution,min_diff"))
+    for i in range(len(max_resolutions)):
+        print "%g,%g" % (max_resolutions[i], differences[i])
+
+    if output:
+        header = "resolution,variance\n"
+        of = open(output, 'w')
+        of.write(header)
+        for i in range(len(resolutions)):
+            output_string = template_string % (resolutions[i], variances[i])
+            of.write(output_string)
+        of.close()
+
+    if plot_output:
+        plt.plot(resolutions, variances)
+        plt.xlabel("Resolution")
+        plt.ylabel("Variance")
+        plt.grid(True)
+        if plot_output == '-':
+            plt.show()
+        else:
+            plt.savefig(plot_output)
+
+		
+
+if __name__ == "__main__":
+    options, flags = gscript.parser()
+    atexit.register(cleanup)
+    main()


Property changes on: grass-addons/grass7/imagery/i.variance/i.variance.py
___________________________________________________________________
Added: svn:executable
   + *
Added: svn:mime-type
   + text/x-python
Added: svn:eol-style
   + native

Added: grass-addons/grass7/imagery/i.variance/i_variance_plot.png
===================================================================
(Binary files differ)


Property changes on: grass-addons/grass7/imagery/i.variance/i_variance_plot.png
___________________________________________________________________
Added: svn:mime-type
   + image/png



More information about the grass-commit mailing list