i.spectral.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. #% required : no
  32. #%end
  33. #%option G_OPT_F_OUTPUT
  34. #% key: output
  35. #% description: Name for output PNG image
  36. #% required : no
  37. #%end
  38. #%option G_OPT_M_EN
  39. #% required : yes
  40. #%end
  41. #%flag
  42. #%key: c
  43. #%description: Label with coordinates instead of numbering
  44. #%end
  45. #%flag
  46. #%key: g
  47. #%description: Use gnuplot for display
  48. #%end
  49. import sys
  50. import os
  51. import atexit
  52. import glob
  53. from grass.script import core as grass
  54. def cleanup():
  55. grass.try_remove('spectrum.gnuplot')
  56. for name in glob.glob('data_[0-9]*'):
  57. if name[5:].isdigit():
  58. grass.try_remove(name)
  59. grass.try_remove('data_x')
  60. for name in glob.glob('data_y_[0-9]*'):
  61. if name[7:].isdigit():
  62. grass.try_remove(name)
  63. def draw_gnuplot(what, xlabels, output, label):
  64. xrange = 0
  65. for i, row in enumerate(what):
  66. outfile = 'data_%d' % i
  67. outf = file(outfile, 'w')
  68. xrange = max(xrange, len(row) - 2)
  69. for j, val in enumerate(row[3:]):
  70. outf.write("%d %s\n" % (j + 1, val))
  71. outf.close()
  72. # build gnuplot script
  73. lines = []
  74. if output:
  75. lines += [
  76. "set term png large",
  77. "set output '%s'" % output
  78. ]
  79. lines += [
  80. "set xtics (%s)" % xlabels,
  81. "set grid",
  82. "set title 'Spectral signatures'",
  83. "set xrange [0:%d]" % xrange,
  84. "set noclabel",
  85. "set xlabel 'Bands'",
  86. "set ylabel 'DN Value'",
  87. "set style data lines"
  88. ]
  89. cmd = []
  90. for i, row in enumerate(what):
  91. if not label:
  92. title = str(i + 1)
  93. else:
  94. title = str(tuple(row[0:2]))
  95. cmd.append("'data_%d' title '%s'" % (i, title))
  96. cmd = ','.join(cmd)
  97. cmd = ' '.join(['plot', cmd, "with linespoints pt 779"])
  98. lines.append(cmd)
  99. plotfile = 'spectrum.gnuplot'
  100. plotf = file(plotfile, 'w')
  101. for line in lines:
  102. plotf.write(line + '\n')
  103. plotf.close()
  104. if output:
  105. grass.call(['gnuplot', plotfile])
  106. else:
  107. grass.call(['gnuplot', '-persist', plotfile])
  108. def draw_linegraph(what):
  109. yfiles = []
  110. xfile = 'data_x'
  111. xf = file(xfile, 'w')
  112. for j, val in enumerate(what[0][3:]):
  113. xf.write("%d\n" % (j + 1))
  114. xf.close()
  115. for i, row in enumerate(what):
  116. yfile = 'data_y_%d' % i
  117. yf = file(yfile, 'w')
  118. for j, val in enumerate(row[3:]):
  119. yf.write("%s\n" % val)
  120. yf.close()
  121. yfiles.append(yfile)
  122. sienna = '#%02x%02x%02x' % (160, 82, 45)
  123. coral = '#%02x%02x%02x' % (255, 127, 80)
  124. gp_colors = ['red', 'green', 'blue', 'magenta', 'cyan', sienna, 'orange', coral]
  125. colors = gp_colors
  126. while len(what) > len(colors):
  127. colors += gp_colors
  128. colors = colors[0:len(what)]
  129. grass.run_command('d.linegraph', x_file = xfile, y_file = yfiles,
  130. y_color = colors, title = 'Spectral signatures',
  131. x_title = 'Bands', y_title = 'DN Value')
  132. def main():
  133. group = options['group']
  134. raster = options['raster']
  135. output = options['output']
  136. coords = options['coords']
  137. label = flags['c']
  138. gnuplot = flags['g']
  139. if not group and not raster:
  140. grass.fatal(_("Either group= or raster= is required"))
  141. if group and raster:
  142. grass.fatal(_("group= and raster= are mutually exclusive"))
  143. #check if present
  144. if gnuplot and not grass.find_program('gnuplot', ['-V']):
  145. grass.fatal(_("gnuplot required, please install first"))
  146. tmp1 = grass.tempfile()
  147. tmp2 = grass.tempfile()
  148. # get y-data for gnuplot-data file
  149. # get data from group files and set the x-axis labels
  150. if group:
  151. # ## PARSES THE GROUP FILES - gets rid of ugly header info from group list output
  152. s = grass.read_command('i.group', flags='g', group = group, quiet = True)
  153. rastermaps = s.splitlines()
  154. else:
  155. # ## get data from list of files and set the x-axis labels
  156. rastermaps = raster.split(',')
  157. xlabels = ["'%s' %d" % (n, i + 1) for i, n in enumerate(rastermaps)]
  158. xlabels = ','.join(xlabels)
  159. numbands = len(rastermaps)
  160. what = []
  161. s = grass.read_command('r.what', input = rastermaps, east_north = coords, quiet = True)
  162. for l in s.splitlines():
  163. f = l.split('|')
  164. for i, v in enumerate(f):
  165. if v in ['', '*']:
  166. f[i] = 0
  167. else:
  168. f[i] = float(v)
  169. what.append(f)
  170. # build data files
  171. if gnuplot:
  172. draw_gnuplot(what, xlabels, output, label)
  173. else:
  174. draw_linegraph(what)
  175. if __name__ == "__main__":
  176. options, flags = grass.parser()
  177. atexit.register(cleanup)
  178. main()