i.colors.enhance.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: i.colors.enhance (former i.landsat.rgb)
  5. #
  6. # AUTHOR(S): Markus Neteler, original author
  7. # Hamish Bowman, scripting enhancements
  8. # Converted to Python by Glynn Clements
  9. #
  10. # PURPOSE: create pretty RGBs: the trick is to remove outliers
  11. # using percentiles (area under the histogram curve)
  12. #
  13. # COPYRIGHT: (C) 2006, 2008, 2012-2014 by the GRASS Development Team
  14. #
  15. # This program is free software under the GNU General Public
  16. # License (>=v2). Read the file COPYING that comes with GRASS
  17. # for details.
  18. #
  19. # TODO: implement better brightness control
  20. #############################################################################
  21. #%module
  22. #% description: Performs auto-balancing of colors for RGB images.
  23. #% keywords: imagery
  24. #% keywords: RGB
  25. #% keywords: satellite
  26. #% keywords: colors
  27. #%end
  28. #%option G_OPT_R_INPUT
  29. #% key: red
  30. #% description: Name of red channel
  31. #%end
  32. #%option G_OPT_R_INPUT
  33. #% key: green
  34. #% description: Name of green channel
  35. #%end
  36. #%option G_OPT_R_INPUT
  37. #% key: blue
  38. #% description: Name of blue channel
  39. #%end
  40. #%option
  41. #% key: strength
  42. #% type: double
  43. #% description: Cropping intensity (upper brightness level)
  44. #% options: 0-100
  45. #% answer : 98
  46. #% required: no
  47. #%end
  48. #%flag
  49. #% key: f
  50. #% description: Extend colors to full range of data on each channel
  51. #% guisection: Colors
  52. #%end
  53. #%flag
  54. #% key: p
  55. #% description: Preserve relative colors, adjust brightness only
  56. #% guisection: Colors
  57. #%end
  58. #%flag
  59. #% key: r
  60. #% description: Reset to standard color range
  61. #% guisection: Colors
  62. #%end
  63. #%flag
  64. #% key: s
  65. #% description: Process bands serially (default: run in parallel)
  66. #%end
  67. import sys
  68. import os
  69. import string
  70. import grass.script as grass
  71. try:
  72. # new for python 2.6, in 2.5 it may be easy_install'd.
  73. import multiprocessing as mp
  74. do_mp = True
  75. except:
  76. do_mp = False
  77. def get_percentile(map, percentiles):
  78. # todo: generalize for any list length
  79. val1 = percentiles[0]
  80. val2 = percentiles[1]
  81. values = '%s,%s' % (val1, val2)
  82. s = grass.read_command('r.univar', flags = 'ge',
  83. map = map, percentile = values)
  84. kv = grass.parse_key_val(s)
  85. # cleanse to match what the key name will become
  86. val_str1 = ('percentile_%.15g' % float(val1)).replace('.','_')
  87. val_str2 = ('percentile_%.15g' % float(val2)).replace('.','_')
  88. return (float(kv[val_str1]), float(kv[val_str2]))
  89. # wrapper to handle multiprocesses communications back to the parent
  90. def get_percentile_mp(map, percentiles, conn):
  91. # Process() doesn't like storing connection parts in
  92. # separate dictionaries, only wants to pass through tuples,
  93. # so instead of just sending the sending the pipe we have to
  94. # send both parts then keep the one we want. ??
  95. output_pipe, input_pipe = conn
  96. input_pipe.close()
  97. result = get_percentile(map, percentiles)
  98. grass.debug('child (%s) (%.1f, %.1f)' % (map, result[0], result[1]))
  99. output_pipe.send(result)
  100. output_pipe.close()
  101. def set_colors(map, v0, v1):
  102. rules = [
  103. "0% black\n",
  104. "%f black\n" % v0,
  105. "%f white\n" % v1,
  106. "100% white\n"
  107. ]
  108. rules = ''.join(rules)
  109. grass.write_command('r.colors', map = map, rules = '-', stdin = rules, quiet = True)
  110. def main():
  111. red = options['red']
  112. green = options['green']
  113. blue = options['blue']
  114. brightness = options['strength']
  115. full = flags['f']
  116. preserve = flags['p']
  117. reset = flags['r']
  118. global do_mp
  119. if flags['s']:
  120. do_mp = False
  121. # 90 or 98? MAX value controls brightness
  122. # think of percent (0-100), must be positive or 0
  123. # must be more than "2" ?
  124. if full:
  125. for i in [red, green, blue]:
  126. grass.run_command('r.colors', map = i, color = 'grey', quiet = True)
  127. sys.exit(0)
  128. if reset:
  129. for i in [red, green, blue]:
  130. grass.run_command('r.colors', map = i, color = 'grey255', quiet = True)
  131. sys.exit(0)
  132. if not preserve:
  133. if do_mp:
  134. grass.message(_("Processing..."))
  135. # set up jobs and launch them
  136. proc = {}
  137. conn = {}
  138. for i in [red, green, blue]:
  139. conn[i] = mp.Pipe()
  140. proc[i] = mp.Process(target = get_percentile_mp,
  141. args = (i, ['2', brightness],
  142. conn[i],))
  143. proc[i].start()
  144. grass.percent(1, 2, 1)
  145. # collect results and wait for jobs to finish
  146. for i in [red, green, blue]:
  147. output_pipe, input_pipe = conn[i]
  148. (v0, v1) = input_pipe.recv()
  149. grass.debug('parent (%s) (%.1f, %.1f)' % (i, v0, v1))
  150. input_pipe.close()
  151. proc[i].join()
  152. set_colors(i, v0, v1)
  153. grass.percent(1, 1, 1)
  154. else:
  155. for i in [red, green, blue]:
  156. grass.message(_("Processing..."))
  157. (v0, v1) = get_percentile(i, ['2', brightness])
  158. grass.debug("<%s>: min=%f max=%f" % (i, v0, v1))
  159. set_colors(i, v0, v1)
  160. else:
  161. all_max = 0
  162. all_min = 999999
  163. if do_mp:
  164. grass.message(_("Processing..."))
  165. # set up jobs and launch jobs
  166. proc = {}
  167. conn = {}
  168. for i in [red, green, blue]:
  169. conn[i] = mp.Pipe()
  170. proc[i] = mp.Process(target = get_percentile_mp,
  171. args = (i, ['2', brightness],
  172. conn[i],))
  173. proc[i].start()
  174. grass.percent(1, 2, 1)
  175. # collect results and wait for jobs to finish
  176. for i in [red, green, blue]:
  177. output_pipe, input_pipe = conn[i]
  178. (v0, v1) = input_pipe.recv()
  179. grass.debug('parent (%s) (%.1f, %.1f)' % (i, v0, v1))
  180. input_pipe.close()
  181. proc[i].join()
  182. all_min = min(all_min, v0)
  183. all_max = max(all_max, v1)
  184. grass.percent(1, 1, 1)
  185. else:
  186. for i in [red, green, blue]:
  187. grass.message(_("Processing..."))
  188. (v0, v1) = get_percentile(i, ['2', brightness])
  189. grass.debug("<%s>: min=%f max=%f" % (i, v0, v1))
  190. all_min = min(all_min, v0)
  191. all_max = max(all_max, v1)
  192. grass.debug("all_min=%f all_max=%f" % (all_min, all_max))
  193. for i in [red, green, blue]:
  194. set_colors(i, all_min, all_max)
  195. # write cmd history:
  196. mapset = grass.gisenv()['MAPSET']
  197. for i in [red, green, blue]:
  198. if grass.find_file(i)['mapset'] == mapset:
  199. grass.raster_history(i)
  200. if __name__ == "__main__":
  201. options, flags = grass.parser()
  202. main()