i.spectral.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: i.spectral
  5. # AUTHOR(S): Markus Neteler, 18. August 1998
  6. # Converted to Python by Glynn Clements
  7. # PURPOSE: displays spectral response at user specified locations in group or images
  8. # COPYRIGHT: (C) 1999 by the GRASS Development Team
  9. #
  10. # This program is free software under the GNU General Public
  11. # License (>=v2). Read the file COPYING that comes with GRASS
  12. # for details.
  13. #
  14. #############################################################################
  15. # written by Markus Neteler 18. August 1998
  16. # neteler geog.uni-hannover.de
  17. #
  18. # bugfix: 25. Nov.98/20. Jan. 1999
  19. # 3 March 2006: Added multiple images and group support by Francesco Pirotti - CIRGEO
  20. # this script needs gnuplot
  21. #%Module
  22. #% description: Displays spectral response at user specified locations in group or images.
  23. #% keywords: imagery
  24. #% keywords: raster
  25. #% keywords: multispectral
  26. #%End
  27. #%option G_OPT_I_GROUP
  28. #% required : no
  29. #%end
  30. #%option G_OPT_R_INPUTS
  31. #% key: raster
  32. #% required : no
  33. #%end
  34. #%option G_OPT_F_OUTPUT
  35. #% key: output
  36. #% description: Name for output PNG image
  37. #% required : no
  38. #%end
  39. #%option G_OPT_M_EN
  40. #% required : yes
  41. #%end
  42. #%flag
  43. #%key: c
  44. #%description: Label with coordinates instead of numbering
  45. #%end
  46. #%flag
  47. #%key: g
  48. #%description: Use gnuplot for display
  49. #%end
  50. import sys
  51. import os
  52. import atexit
  53. import glob
  54. from grass.script import core as grass
  55. def cleanup():
  56. grass.try_remove('spectrum.gnuplot')
  57. for name in glob.glob('data_[0-9]*'):
  58. if name[5:].isdigit():
  59. grass.try_remove(name)
  60. grass.try_remove('data_x')
  61. for name in glob.glob('data_y_[0-9]*'):
  62. if name[7:].isdigit():
  63. grass.try_remove(name)
  64. def draw_gnuplot(what, xlabels, output, label):
  65. xrange = 0
  66. for i, row in enumerate(what):
  67. outfile = 'data_%d' % i
  68. outf = file(outfile, 'w')
  69. xrange = max(xrange, len(row) - 2)
  70. for j, val in enumerate(row[3:]):
  71. outf.write("%d %s\n" % (j + 1, val))
  72. outf.close()
  73. # build gnuplot script
  74. lines = []
  75. if output:
  76. lines += [
  77. "set term png large",
  78. "set output '%s'" % output
  79. ]
  80. lines += [
  81. "set xtics (%s)" % xlabels,
  82. "set grid",
  83. "set title 'Spectral signatures'",
  84. "set xrange [0:%d]" % xrange,
  85. "set noclabel",
  86. "set xlabel 'Bands'",
  87. "set ylabel 'DN Value'",
  88. "set style data lines"
  89. ]
  90. cmd = []
  91. for i, row in enumerate(what):
  92. if not label:
  93. title = str(i + 1)
  94. else:
  95. title = str(tuple(row[0:2]))
  96. cmd.append("'data_%d' title '%s'" % (i, title))
  97. cmd = ','.join(cmd)
  98. cmd = ' '.join(['plot', cmd, "with linespoints pt 779"])
  99. lines.append(cmd)
  100. plotfile = 'spectrum.gnuplot'
  101. plotf = file(plotfile, 'w')
  102. for line in lines:
  103. plotf.write(line + '\n')
  104. plotf.close()
  105. if output:
  106. grass.call(['gnuplot', plotfile])
  107. else:
  108. grass.call(['gnuplot', '-persist', plotfile])
  109. def draw_linegraph(what):
  110. yfiles = []
  111. xfile = 'data_x'
  112. xf = file(xfile, 'w')
  113. for j, val in enumerate(what[0][3:]):
  114. xf.write("%d\n" % (j + 1))
  115. xf.close()
  116. for i, row in enumerate(what):
  117. yfile = 'data_y_%d' % i
  118. yf = file(yfile, 'w')
  119. for j, val in enumerate(row[3:]):
  120. yf.write("%s\n" % val)
  121. yf.close()
  122. yfiles.append(yfile)
  123. sienna = '#%02x%02x%02x' % (160, 82, 45)
  124. coral = '#%02x%02x%02x' % (255, 127, 80)
  125. gp_colors = ['red', 'green', 'blue', 'magenta', 'cyan', sienna, 'orange', coral]
  126. colors = gp_colors
  127. while len(what) > len(colors):
  128. colors += gp_colors
  129. colors = colors[0:len(what)]
  130. grass.run_command('d.linegraph', x_file = xfile, y_file = yfiles,
  131. y_color = colors, title = 'Spectral signatures',
  132. x_title = 'Bands', y_title = 'DN Value')
  133. def main():
  134. group = options['group']
  135. raster = options['raster']
  136. output = options['output']
  137. coords = options['east_north']
  138. label = flags['c']
  139. gnuplot = flags['g']
  140. if not group and not raster:
  141. grass.fatal(_("Either group= or raster= is required"))
  142. if group and raster:
  143. grass.fatal(_("group= and raster= are mutually exclusive"))
  144. #check if present
  145. if gnuplot and not grass.find_program('gnuplot', ['-V']):
  146. grass.fatal(_("gnuplot required, please install first"))
  147. tmp1 = grass.tempfile()
  148. tmp2 = grass.tempfile()
  149. # get y-data for gnuplot-data file
  150. # get data from group files and set the x-axis labels
  151. if group:
  152. # ## PARSES THE GROUP FILES - gets rid of ugly header info from group list output
  153. s = grass.read_command('i.group', flags='g', group = group, quiet = True)
  154. rastermaps = s.splitlines()
  155. else:
  156. # ## get data from list of files and set the x-axis labels
  157. rastermaps = raster.split(',')
  158. xlabels = ["'%s' %d" % (n, i + 1) for i, n in enumerate(rastermaps)]
  159. xlabels = ','.join(xlabels)
  160. numbands = len(rastermaps)
  161. what = []
  162. s = grass.read_command('r.what', input = rastermaps, east_north = coords, quiet = True)
  163. for l in s.splitlines():
  164. f = l.split('|')
  165. for i, v in enumerate(f):
  166. if v in ['', '*']:
  167. f[i] = 0
  168. else:
  169. f[i] = float(v)
  170. what.append(f)
  171. # build data files
  172. if gnuplot:
  173. draw_gnuplot(what, xlabels, output, label)
  174. else:
  175. draw_linegraph(what)
  176. if __name__ == "__main__":
  177. options, flags = grass.parser()
  178. atexit.register(cleanup)
  179. main()