i.pansharpen.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: i.pansharpen
  5. #
  6. # AUTHOR(S): Overall script by Michael Barton (ASU)
  7. # Brovey transformation in i.fusion.brovey by Markus Neteler <<neteler at osgeo org>>
  8. # i.fusion brovey converted to Python by Glynn Clements
  9. # IHS and PCA transformation added by Michael Barton (ASU)
  10. # histogram matching algorithm by Michael Barton and Luca Delucchi, Fondazione E. Mach (Italy)
  11. # Thanks to Markus Metz for help with PCA inversion
  12. # Thanks to Hamish Bowman for parallel processing algorithm
  13. #
  14. # PURPOSE: Sharpening of 3 RGB channels using a high-resolution panchromatic channel
  15. #
  16. # COPYRIGHT: (C) 2002-2012 by the GRASS Development Team
  17. #
  18. # This program is free software under the GNU General Public
  19. # License (>=v2). Read the file COPYING that comes with GRASS
  20. # for details.
  21. #
  22. # REFERENCES:
  23. # Roller, N.E.G. and Cox, S., 1980. Comparison of Landsat MSS and merged MSS/RBV
  24. # data for analysis of natural vegetation. Proc. of the 14th International
  25. # Symposium on Remote Sensing of Environment, San Jose, Costa Rica, 23-30 April, pp. 1001-1007.
  26. #
  27. # Amarsaikhan, D., & Douglas, T. (2004). Data fusion and multisource image classification.
  28. # International Journal of Remote Sensing, 25(17), 3529-3539.
  29. #
  30. # Behnia, P. (2005). Comparison between four methods for data fusion of ETM+
  31. # multispectral and pan images. Geo-spatial Information Science, 8(2), 98-103
  32. #
  33. # for LANDSAT 5: see Pohl, C 1996 and others
  34. #
  35. #############################################################################
  36. #%Module
  37. #% description: Image fusion algorithms to sharpen multispectral with high-res panchromatic channels
  38. #% keywords: imagery
  39. #% keywords: fusion
  40. #% keywords: sharpen
  41. #% keywords: Brovey
  42. #% keywords: IHS
  43. #% keywords: PCA
  44. #% overwrite: yes
  45. #%End
  46. #%option
  47. #% key: sharpen
  48. #% description: Choose pan sharpening method
  49. #% options: brovey,ihs,pca
  50. #% answer: ihs
  51. #% required: yes
  52. #%end
  53. #%option G_OPT_R_INPUT
  54. #% key: ms3
  55. #% description: Input raster map for red channel
  56. #%end
  57. #%option G_OPT_R_INPUT
  58. #% key: ms2
  59. #% description: Input raster map for green channel
  60. #%end
  61. #%option G_OPT_R_INPUT
  62. #% key: ms1
  63. #% description: Input raster map for blue channel
  64. #%end
  65. #% option G_OPT_R_INPUT
  66. #% key: pan
  67. #% description: Input raster map for high resolution panchromatic channel
  68. #%end
  69. #%option
  70. #% key: output_prefix
  71. #% type: string
  72. #% description: Prefix for output raster maps
  73. #% required : yes
  74. #%end
  75. #%flag
  76. #% key: s
  77. #% description: Serial processing rather than parallel processing
  78. #%end
  79. #%flag
  80. #% key: l
  81. #% description: Rebalance blue channel for landsat maps
  82. #%end
  83. import sys
  84. import os
  85. import numpy as np
  86. import grass.script as grass
  87. def main():
  88. sharpen = options['sharpen'] # sharpening algorithm
  89. ms1 = options['ms1'] # blue channel
  90. ms2 = options['ms2'] # green channel
  91. ms3 = options['ms3'] # red channel
  92. pan = options['pan'] # high res pan channel
  93. out = options['output_prefix'] # prefix for output RGB maps
  94. bladjust = flags['l'] # adjust blue channel
  95. sproc = flags['s'] # serial processing
  96. outb = grass.core.find_file('%s_blue' % out)
  97. outg = grass.core.find_file('%s_green' % out)
  98. outr = grass.core.find_file('%s_red' % out)
  99. if (outb['name'] != '' or outg['name'] != '' or outr['name'] != '') and \
  100. (not grass.overwrite() and not flags['o']):
  101. grass.warning(_('Maps with selected output prefix names already exist. \
  102. Delete them or use overwrite flag'))
  103. return
  104. pid = str(os.getpid())
  105. #get PAN resolution:
  106. kv = grass.raster_info(map = pan)
  107. nsres = kv['nsres']
  108. ewres = kv['ewres']
  109. panres = (nsres + ewres) / 2
  110. # clone current region
  111. grass.use_temp_region()
  112. grass.run_command('g.region', res = panres, align = pan)
  113. grass.message('\n ')
  114. grass.message(_("Performing pan sharpening with hi res pan image: %f" % panres))
  115. if sharpen == "brovey":
  116. grass.message(_("Using Brovey algorithm"))
  117. #pan/intensity histogram matching using linear regression
  118. outname = 'tmp%s_pan1' % pid
  119. panmatch1 = matchhist(pan, ms1, outname)
  120. outname = 'tmp%s_pan2' % pid
  121. panmatch2 = matchhist(pan, ms2, outname)
  122. outname = 'tmp%s_pan3' % pid
  123. panmatch3 = matchhist(pan, ms3, outname)
  124. outr = '%s_red' % out
  125. outg = '%s_green' % out
  126. outb = '%s_blue' % out
  127. #calculate brovey transformation
  128. grass.message('\n ')
  129. grass.message(_("Calculating Brovey transformation..."))
  130. if sproc:
  131. # serial processing
  132. e = '''eval(k = "$ms1" + "$ms2" + "$ms3")
  133. "$outr" = 1.0 * "$ms3" * "$panmatch3" / k
  134. "$outg" = 1.0 * "$ms2" * "$panmatch2" / k
  135. "$outb" = 1.0 * "$ms1" * "$panmatch1" / k'''
  136. grass.mapcalc(e, outr=outr, outg=outg, outb=outb,
  137. panmatch1=panmatch1, panmatch2=panmatch2, panmatch3=panmatch3,
  138. ms1=ms1, ms2=ms2, ms3=ms3, overwrite=True)
  139. else:
  140. # parallel processing
  141. pb = grass.mapcalc_start('%s_blue = (1.0 * %s * %s) / (%s + %s + %s)' %
  142. (out, ms1, panmatch1, ms1, ms2, ms3),
  143. overwrite=True)
  144. pg = grass.mapcalc_start('%s_green = (1.0 * %s * %s) / (%s + %s + %s)' %
  145. (out, ms2, panmatch2, ms1, ms2, ms3),
  146. overwrite=True)
  147. pr = grass.mapcalc_start('%s_red = (1.0 * %s * %s) / (%s + %s + %s)' %
  148. (out, ms3, panmatch3, ms1, ms2, ms3),
  149. overwrite=True)
  150. pb.wait()
  151. pg.wait()
  152. pr.wait()
  153. # Cleanup
  154. grass.run_command('g.remove', quiet=True, rast='%s,%s,%s' % (panmatch1, panmatch2, panmatch3))
  155. elif sharpen == "ihs":
  156. grass.message(_("Using IHS<->RGB algorithm"))
  157. #transform RGB channels into IHS color space
  158. grass.message('\n ')
  159. grass.message(_("Transforming to IHS color space..."))
  160. grass.run_command('i.rgb.his', overwrite=True,
  161. red_input=ms3,
  162. green_input=ms2,
  163. blue_input=ms1,
  164. hue_output="tmp%s_hue" % pid,
  165. intensity_output="tmp%s_int" % pid,
  166. saturation_output="tmp%s_sat" % pid)
  167. #pan/intensity histogram matching using linear regression
  168. target = "tmp%s_int" % pid
  169. outname = "tmp%s_pan_int" % pid
  170. panmatch = matchhist(pan, target, outname)
  171. #substitute pan for intensity channel and transform back to RGB color space
  172. grass.message('\n ')
  173. grass.message(_("Transforming back to RGB color space and sharpening..."))
  174. grass.run_command('i.his.rgb', overwrite=True,
  175. hue_input="tmp%s_hue" % pid,
  176. intensity_input="%s" % panmatch,
  177. saturation_input="tmp%s_sat" % pid,
  178. red_output="%s_red" % out,
  179. green_output="%s_green" % out,
  180. blue_output="%s_blue" % out)
  181. # Cleanup
  182. grass.run_command('g.remove', quiet=True, rast=panmatch)
  183. elif sharpen == "pca":
  184. grass.message(_("Using PCA/inverse PCA algorithm"))
  185. grass.message('\n ')
  186. grass.message(_("Creating PCA images and calculating eigenvectors..."))
  187. #initial PCA with RGB channels
  188. pca_out = grass.read_command('i.pca', quiet=True, rescale='0,0', input='%s,%s,%s' % (ms1, ms2, ms3), output_prefix='tmp%s.pca' % pid)
  189. b1evect = []
  190. b2evect = []
  191. b3evect = []
  192. for l in pca_out.replace('(',',').replace(')',',').splitlines():
  193. b1evect.append(float(l.split(',')[1]))
  194. b2evect.append(float(l.split(',')[2]))
  195. b3evect.append(float(l.split(',')[3]))
  196. #inverse PCA with hi res pan channel substituted for principal component 1
  197. pca1 = 'tmp%s.pca.1' % pid
  198. pca2 = 'tmp%s.pca.2' % pid
  199. pca3 = 'tmp%s.pca.3' % pid
  200. b1evect1 = b1evect[0]
  201. b1evect2 = b1evect[1]
  202. b1evect3 = b1evect[2]
  203. b2evect1 = b2evect[0]
  204. b2evect2 = b2evect[1]
  205. b2evect3 = b2evect[2]
  206. b3evect1 = b3evect[0]
  207. b3evect2 = b3evect[1]
  208. b3evect3 = b3evect[2]
  209. outname = 'tmp%s_pan' % pid
  210. panmatch = matchhist(pan, ms1, outname)
  211. grass.message('\n ')
  212. grass.message(_("Performing inverse PCA ..."))
  213. stats1 = grass.parse_command("r.univar", map=ms1, flags='g',
  214. parse=(grass.parse_key_val, { 'sep' : '=' }))
  215. stats2 = grass.parse_command("r.univar", map=ms2, flags='g',
  216. parse=(grass.parse_key_val, { 'sep' : '=' }))
  217. stats3 = grass.parse_command("r.univar", map=ms3, flags='g',
  218. parse=(grass.parse_key_val, { 'sep' : '=' }))
  219. b1mean = float(stats1['mean'])
  220. b2mean = float(stats2['mean'])
  221. b3mean = float(stats3['mean'])
  222. if sproc:
  223. # serial processing
  224. e = '''eval(k = "$ms1" + "$ms2" + "$ms3")
  225. "$outr" = 1.0 * "$ms3" * "$panmatch3" / k
  226. "$outg" = 1.0 * "$ms2" * "$panmatch2" / k
  227. "$outb" = 1.0* "$ms1" * "$panmatch1" / k'''
  228. outr = '%s_red' % out
  229. outg = '%s_green' % out
  230. outb = '%s_blue' % out
  231. cmd1 = "$outb = (1.0 * $panmatch * $b1evect1) + ($pca2 * $b2evect1) + ($pca3 * $b3evect1) + $b1mean"
  232. cmd2 = "$outg = (1.0 * $panmatch * $b1evect2) + ($pca2 * $b2evect1) + ($pca3 * $b3evect2) + $b2mean"
  233. cmd3 = "$outr = (1.0 * $panmatch * $b1evect3) + ($pca2 * $b2evect3) + ($pca3 * $b3evect3) + $b3mean"
  234. cmd = '\n'.join([cmd1, cmd2, cmd3])
  235. grass.mapcalc(cmd, outb=outb, outg=outg, outr=outr,
  236. panmatch=panmatch, pca2=pca2, pca3=pca3,
  237. b1evect1=b1evect1, b2evect1=b2evect1, b3evect1=b3evect1,
  238. b1evect2=b1evect2, b2evect2=b2evect2, b3evect2=b3evect2,
  239. b1evect3=b1evect3, b2evect3=b2evect3, b3evect3=b3evect3,
  240. b1mean=b1mean, b2mean=b2mean, b3mean=b3mean,
  241. overwrite=True)
  242. else:
  243. # parallel processing
  244. pb = grass.mapcalc_start('%s_blue = (%s * %f) + (%s * %f) + (%s * %f) + %f'
  245. % (out, panmatch, b1evect1, pca2, b2evect1, pca3, b3evect1, b1mean),
  246. overwrite=True)
  247. pg = grass.mapcalc_start('%s_green = (%s * %f) + (%s * %f) + (%s * %f) + %f'
  248. % (out, panmatch, b1evect2, pca2, b2evect2, pca3, b3evect2, b2mean),
  249. overwrite=True)
  250. pr = grass.mapcalc_start('%s_red = (%s * %f) + (%s * %f) + (%s * %f) + %f'
  251. % (out, panmatch, b1evect3, pca2, b2evect3, pca3, b3evect3, b3mean),
  252. overwrite=True)
  253. pr.wait()
  254. pg.wait()
  255. pb.wait()
  256. # Cleanup
  257. grass.run_command('g.mremove', flags='f', quiet=True, rast='tmp%s*,%s' % (pid,panmatch))
  258. #Could add other sharpening algorithms here, e.g. wavelet transformation
  259. grass.message('\n ')
  260. grass.message(_("Assigning grey equalized color tables to output images..."))
  261. #equalized grey scales give best contrast
  262. for ch in ['red', 'green', 'blue']:
  263. grass.run_command('r.colors', quiet=True, map = "%s_%s" % (out, ch), flags="e", col = 'grey')
  264. #Landsat too blue-ish because panchromatic band less sensitive to blue light,
  265. # so output blue channed can be modified
  266. if bladjust:
  267. grass.message('\n ')
  268. grass.message(_("Adjusting blue channel color table..."))
  269. rules = grass.tempfile()
  270. colors = open(rules, 'w')
  271. colors.write('5 0 0 0\n20 200 200 200\n40 230 230 230\n67 255 255 255 \n')
  272. colors.close()
  273. grass.run_command('r.colors', map="%s_blue" % out, rules=rules)
  274. os.remove(rules)
  275. #output notice
  276. grass.message('\n ')
  277. grass.message(_("The following pan-sharpened output maps have been generated:"))
  278. for ch in ['red', 'green', 'blue']:
  279. grass.message(_("%s_%s") % (out, ch))
  280. grass.message('\n ')
  281. grass.message(_("To visualize output, run: g.region -p rast=%s.red" % out))
  282. grass.message(_("d.rgb r=%s_red g=%s_green b=%s_blue" % (out, out, out)))
  283. grass.message('\n ')
  284. grass.message(_("If desired, combine channels into a single RGB map with 'r.composite'."))
  285. grass.message(_("Channel colors can be rebalanced using i.landsat.rgb."))
  286. # write cmd history:
  287. for ch in ['red', 'green', 'blue']:
  288. grass.raster_history("%s_%s" % (out, ch))
  289. # Cleanup
  290. grass.run_command('g.mremove', flags="f", rast="tmp%s*" % pid, quiet=True)
  291. def matchhist(original, target, matched):
  292. #pan/intensity histogram matching using numpy arrays
  293. grass.message('\n ')
  294. grass.message(_("Histogram matching..."))
  295. # input images
  296. original = original.split('@')[0]
  297. target = target.split('@')[0]
  298. images = [original, target]
  299. # create a dictionary to hold arrays for each image
  300. arrays = {}
  301. for i in images:
  302. # calculate number of cells for each grey value for for each image
  303. stats_out = grass.pipe_command('r.stats', flags='cin', input= i, sep=':')
  304. stats = stats_out.communicate()[0].split('\n')[:-1]
  305. stats_dict = dict( s.split(':', 1) for s in stats)
  306. total_cells = 0 # total non-null cells
  307. for j in stats_dict:
  308. stats_dict[j] = int(stats_dict[j])
  309. if j != '*':
  310. total_cells += stats_dict[j]
  311. # Make a 2x256 structured array for each image with a
  312. # cumulative distribution function (CDF) for each grey value.
  313. # Grey value is the integer (i4) and cdf is float (f4).
  314. arrays[i] = np.zeros((256,),dtype=('i4,f4'))
  315. cum_cells = 0 # cumulative total of cells for sum of current and all lower grey values
  316. for n in range(0,256):
  317. if str(n) in stats_dict:
  318. num_cells = stats_dict[str(n)]
  319. else:
  320. num_cells = 0
  321. cum_cells += num_cells
  322. # cdf is the the number of cells at or below a given grey value
  323. # divided by the total number of cells
  324. cdf = float(cum_cells) / float(total_cells)
  325. # insert values into array
  326. arrays[i][n] = (n, cdf)
  327. # open file for reclass rules
  328. outfile = open(grass.tempfile(), 'w')
  329. new_grey = 0
  330. for i in arrays[original]:
  331. # for each grey value and corresponding cdf value in original, find the
  332. # cdf value in target that is closest to the target cdf value
  333. difference_list = []
  334. for j in arrays[target]:
  335. # make a list of the difference between each original cdf value and
  336. # the target cdf value
  337. difference_list.append(abs(i[1] - j[1]))
  338. # get the smallest difference in the list
  339. min_difference = min(difference_list)
  340. for j in arrays[target]:
  341. # find the grey value in target that correspondes to the cdf
  342. # closest to the original cdf
  343. if j[1] == i[1] + min_difference or j[1] == i[1] - min_difference:
  344. # build a reclass rules file from the original grey value and
  345. # corresponding grey value from target
  346. out_line = "%d = %d\n" % (i[0], j[0])
  347. outfile.write(out_line)
  348. break
  349. outfile.close()
  350. # create reclass of target from reclass rules file
  351. result = grass.core.find_file(matched, element = 'cell')
  352. if result['fullname']:
  353. grass.run_command('g.remove', quiet=True, rast=matched)
  354. grass.run_command('r.reclass', input=original, out=matched, rules=outfile.name)
  355. else:
  356. grass.run_command('r.reclass', input=original, out=matched, rules=outfile.name)
  357. # Cleanup
  358. # remove the rules file
  359. grass.try_remove(outfile.name)
  360. # return reclass of target with histogram that matches original
  361. return matched
  362. if __name__ == "__main__":
  363. options, flags = grass.parser()
  364. main()