i.spectral.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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 raster images
  9. # COPYRIGHT: (C) 1999-2013 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. #
  17. # this script needs gnuplot for pretty rendering
  18. # TODO: use PyPlot like the wxGUI Profiling tool
  19. #
  20. # written by Markus Neteler 18. August 1998
  21. # neteler geog.uni-hannover.de
  22. #
  23. # bugfix: 25. Nov.98/20. Jan. 1999
  24. # 3 March 2006: Added multiple images and group support by Francesco Pirotti - CIRGEO
  25. #
  26. #%Module
  27. #% description: Displays spectral response at user specified locations in group or images.
  28. #% keyword: imagery
  29. #% keyword: querying
  30. #% keyword: raster
  31. #% keyword: multispectral
  32. #%End
  33. #%option G_OPT_I_GROUP
  34. #% required : no
  35. #% guisection: Input
  36. #%end
  37. #%option G_OPT_R_INPUTS
  38. #% key: raster
  39. #% required : no
  40. #% guisection: Input
  41. #%end
  42. #%option G_OPT_M_COORDS
  43. #% multiple: yes
  44. #% required: yes
  45. #% guisection: Input
  46. #%end
  47. #%option G_OPT_F_OUTPUT
  48. #% key: output
  49. #% description: Name for output image
  50. #% guisection: Output
  51. #% required : no
  52. #%end
  53. #%Option
  54. #% key: format
  55. #% type: string
  56. #% description: Graphics format for output file
  57. #% options: png,eps,svg
  58. #% answer: png
  59. #% multiple: no
  60. #% guisection: Output
  61. #%End
  62. #%flag
  63. #% key: c
  64. #% description: Show sampling coordinates instead of numbering in the legend
  65. #%end
  66. #% flag
  67. #% key: g
  68. #% description: Use gnuplot for display
  69. #%end
  70. import os
  71. import atexit
  72. from grass.script.utils import try_rmdir
  73. from grass.script import core as grass
  74. def cleanup():
  75. try_rmdir(tmp_dir)
  76. def draw_gnuplot(what, xlabels, output, img_format, coord_legend):
  77. xrange = 0
  78. for i, row in enumerate(what):
  79. outfile = os.path.join(tmp_dir, 'data_%d' % i)
  80. outf = open(outfile, 'w')
  81. xrange = max(xrange, len(row) - 2)
  82. for j, val in enumerate(row[3:]):
  83. outf.write("%d %s\n" % (j + 1, val))
  84. outf.close()
  85. # build gnuplot script
  86. lines = []
  87. if output:
  88. if img_format == 'png':
  89. term_opts = "png truecolor large size 825,550"
  90. elif img_format == 'eps':
  91. term_opts = "postscript eps color solid size 6,4"
  92. elif img_format == 'svg':
  93. term_opts = "svg size 825,550 dynamic solid"
  94. else:
  95. grass.fatal(_("Programmer error (%s)") % img_format)
  96. lines += [
  97. "set term " + term_opts,
  98. "set output '%s'" % output
  99. ]
  100. lines += [
  101. "set xtics (%s)" % xlabels,
  102. "set grid",
  103. "set title 'Spectral signatures'",
  104. "set xrange [0.5 : %d - 0.5]" % xrange,
  105. "set noclabel",
  106. "set xlabel 'Bands'",
  107. "set xtics rotate by -40",
  108. "set ylabel 'DN Value'",
  109. "set style data lines"
  110. ]
  111. cmd = []
  112. for i, row in enumerate(what):
  113. if not coord_legend:
  114. title = 'Pick ' + str(i + 1)
  115. else:
  116. title = str(tuple(row[0:2]))
  117. x_datafile = os.path.join(tmp_dir, 'data_%d' % i)
  118. cmd.append(" '%s' title '%s'" % (x_datafile, title))
  119. cmd = ','.join(cmd)
  120. cmd = ' '.join(['plot', cmd, "with linespoints pt 779"])
  121. lines.append(cmd)
  122. plotfile = os.path.join(tmp_dir, 'spectrum.gnuplot')
  123. plotf = open(plotfile, 'w')
  124. for line in lines:
  125. plotf.write(line + '\n')
  126. plotf.close()
  127. if output:
  128. grass.call(['gnuplot', plotfile])
  129. else:
  130. grass.call(['gnuplot', '-persist', plotfile])
  131. def draw_linegraph(what):
  132. yfiles = []
  133. xfile = os.path.join(tmp_dir, 'data_x')
  134. xf = open(xfile, 'w')
  135. for j, val in enumerate(what[0][3:]):
  136. xf.write("%d\n" % (j + 1))
  137. xf.close()
  138. for i, row in enumerate(what):
  139. yfile = os.path.join(tmp_dir, 'data_y_%d' % i)
  140. yf = open(yfile, 'w')
  141. for j, val in enumerate(row[3:]):
  142. yf.write("%s\n" % val)
  143. yf.close()
  144. yfiles.append(yfile)
  145. sienna = '#%02x%02x%02x' % (160, 82, 45)
  146. coral = '#%02x%02x%02x' % (255, 127, 80)
  147. gp_colors = ['red', 'green', 'blue', 'magenta', 'cyan', sienna, 'orange',
  148. coral]
  149. colors = gp_colors
  150. while len(what) > len(colors):
  151. colors += gp_colors
  152. colors = colors[0:len(what)]
  153. grass.run_command('d.linegraph', x_file=xfile, y_file=yfiles,
  154. y_color=colors, title='Spectral signatures',
  155. x_title='Bands', y_title='DN Value')
  156. def main():
  157. group = options['group']
  158. raster = options['raster']
  159. output = options['output']
  160. coords = options['coordinates']
  161. img_fmt = options['format']
  162. coord_legend = flags['c']
  163. gnuplot = flags['g']
  164. global tmp_dir
  165. tmp_dir = grass.tempdir()
  166. if not group and not raster:
  167. grass.fatal(_("Either group= or raster= is required"))
  168. if group and raster:
  169. grass.fatal(_("group= and raster= are mutually exclusive"))
  170. # check if gnuplot is present
  171. if gnuplot and not grass.find_program('gnuplot', '-V'):
  172. grass.fatal(_("gnuplot required, please install first"))
  173. # get data from group listing and set the x-axis labels
  174. if group:
  175. # Parse the group list output
  176. s = grass.read_command('i.group', flags='g', group=group, quiet=True)
  177. rastermaps = s.splitlines()
  178. else:
  179. # get data from list of files and set the x-axis labels
  180. rastermaps = raster.split(',')
  181. xlabels = ["'%s' %d" % (n, i + 1) for i, n in enumerate(rastermaps)]
  182. xlabels = ','.join(xlabels)
  183. # get y-data for gnuplot-data file
  184. what = []
  185. s = grass.read_command('r.what', map=rastermaps, coordinates=coords,
  186. null='0', quiet=True)
  187. if len(s) == 0:
  188. grass.fatal(_('No data returned from query'))
  189. for l in s.splitlines():
  190. f = l.split('|')
  191. for i, v in enumerate(f):
  192. if v in ['', '*']:
  193. f[i] = 0
  194. else:
  195. f[i] = float(v)
  196. what.append(f)
  197. # build data files
  198. if gnuplot:
  199. draw_gnuplot(what, xlabels, output, img_fmt, coord_legend)
  200. else:
  201. draw_linegraph(what)
  202. if __name__ == "__main__":
  203. options, flags = grass.parser()
  204. atexit.register(cleanup)
  205. main()