i.spectral.py 5.7 KB

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