i.spectral.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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 (or text file for -t)
  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. #% flag
  71. #% key: t
  72. #% description: output to text file
  73. #%end
  74. import os
  75. import atexit
  76. from grass.script.utils import try_rmdir
  77. from grass.script import core as gcore
  78. def cleanup():
  79. try_rmdir(tmp_dir)
  80. def write2textf(what, output):
  81. outf = open(output, 'w')
  82. i = 0
  83. for row in enumerate(what):
  84. i = i + 1
  85. outf.write("%d, %s\n" % (i, row))
  86. outf.close()
  87. def draw_gnuplot(what, xlabels, output, img_format, coord_legend):
  88. xrange = 0
  89. for i, row in enumerate(what):
  90. outfile = os.path.join(tmp_dir, 'data_%d' % i)
  91. outf = open(outfile, 'w')
  92. xrange = max(xrange, len(row) - 2)
  93. for j, val in enumerate(row[3:]):
  94. outf.write("%d %s\n" % (j + 1, val))
  95. outf.close()
  96. # build gnuplot script
  97. lines = []
  98. if output:
  99. if img_format == 'png':
  100. term_opts = "png truecolor large size 825,550"
  101. elif img_format == 'eps':
  102. term_opts = "postscript eps color solid size 6,4"
  103. elif img_format == 'svg':
  104. term_opts = "svg size 825,550 dynamic solid"
  105. else:
  106. gcore.fatal(_("Programmer error (%s)") % img_format)
  107. lines += [
  108. "set term " + term_opts,
  109. "set output '%s'" % output
  110. ]
  111. lines += [
  112. "set xtics (%s)" % xlabels,
  113. "set grid",
  114. "set title 'Spectral signatures'",
  115. "set xrange [0.5 : %d - 0.5]" % xrange,
  116. "set noclabel",
  117. "set xlabel 'Bands'",
  118. "set xtics rotate by -40",
  119. "set ylabel 'DN Value'",
  120. "set style data lines"
  121. ]
  122. cmd = []
  123. for i, row in enumerate(what):
  124. if not coord_legend:
  125. title = 'Pick ' + str(i + 1)
  126. else:
  127. title = str(tuple(row[0:2]))
  128. x_datafile = os.path.join(tmp_dir, 'data_%d' % i)
  129. cmd.append(" '%s' title '%s'" % (x_datafile, title))
  130. cmd = ','.join(cmd)
  131. cmd = ' '.join(['plot', cmd, "with linespoints pt 779"])
  132. lines.append(cmd)
  133. plotfile = os.path.join(tmp_dir, 'spectrum.gnuplot')
  134. plotf = open(plotfile, 'w')
  135. for line in lines:
  136. plotf.write(line + '\n')
  137. plotf.close()
  138. if output:
  139. gcore.call(['gnuplot', plotfile])
  140. else:
  141. gcore.call(['gnuplot', '-persist', plotfile])
  142. def draw_linegraph(what):
  143. yfiles = []
  144. xfile = os.path.join(tmp_dir, 'data_x')
  145. xf = open(xfile, 'w')
  146. for j, val in enumerate(what[0][3:]):
  147. xf.write("%d\n" % (j + 1))
  148. xf.close()
  149. for i, row in enumerate(what):
  150. yfile = os.path.join(tmp_dir, 'data_y_%d' % i)
  151. yf = open(yfile, 'w')
  152. for j, val in enumerate(row[3:]):
  153. yf.write("%s\n" % val)
  154. yf.close()
  155. yfiles.append(yfile)
  156. sienna = '#%02x%02x%02x' % (160, 82, 45)
  157. coral = '#%02x%02x%02x' % (255, 127, 80)
  158. gp_colors = ['red', 'green', 'blue', 'magenta', 'cyan', sienna, 'orange',
  159. coral]
  160. colors = gp_colors
  161. while len(what) > len(colors):
  162. colors += gp_colors
  163. colors = colors[0:len(what)]
  164. gcore.run_command('d.linegraph', x_file=xfile, y_file=yfiles,
  165. y_color=colors, title='Spectral signatures',
  166. x_title='Bands', y_title='DN Value')
  167. def main():
  168. group = options['group']
  169. raster = options['raster']
  170. output = options['output']
  171. coords = options['coordinates']
  172. img_fmt = options['format']
  173. coord_legend = flags['c']
  174. gnuplot = flags['g']
  175. textfile = flags['t']
  176. global tmp_dir
  177. tmp_dir = gcore.tempdir()
  178. if not group and not raster:
  179. gcore.fatal(_("Either group= or raster= is required"))
  180. if group and raster:
  181. gcore.fatal(_("group= and raster= are mutually exclusive"))
  182. # -t needs an output filename
  183. if textfile and not output:
  184. gcore.fatal(_("Writing to text file requires output=filename"))
  185. # check if gnuplot is present
  186. if gnuplot and not gcore.find_program('gnuplot', '-V'):
  187. gcore.fatal(_("gnuplot required, please install first"))
  188. # get data from group listing and set the x-axis labels
  189. if group:
  190. # Parse the group list output
  191. s = gcore.read_command('i.group', flags='g', group=group, quiet=True)
  192. rastermaps = s.splitlines()
  193. else:
  194. # get data from list of files and set the x-axis labels
  195. rastermaps = raster.split(',')
  196. xlabels = ["'%s' %d" % (n, i + 1) for i, n in enumerate(rastermaps)]
  197. xlabels = ','.join(xlabels)
  198. # get y-data for gnuplot-data file
  199. what = []
  200. s = gcore.read_command('r.what', map=rastermaps, coordinates=coords,
  201. null='0', quiet=True)
  202. if len(s) == 0:
  203. gcore.fatal(_('No data returned from query'))
  204. for l in s.splitlines():
  205. f = l.split('|')
  206. for i, v in enumerate(f):
  207. if v in ['', '*']:
  208. f[i] = 0
  209. else:
  210. f[i] = float(v)
  211. what.append(f)
  212. # build data files
  213. if gnuplot:
  214. draw_gnuplot(what, xlabels, output, img_fmt, coord_legend)
  215. elif textfile:
  216. write2textf(what, output)
  217. else:
  218. draw_linegraph(what)
  219. if __name__ == "__main__":
  220. options, flags = gcore.parser()
  221. atexit.register(cleanup)
  222. main()