modis_mosaic.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. #!/usr/bin/env python
  2. # script to create mosaic from several tiles of MODIS
  3. #
  4. # (c) Copyright Luca Delucchi 2012
  5. # Authors: Luca Delucchi
  6. # Email: luca dot delucchi at iasma dot it
  7. #
  8. ##################################################################
  9. #
  10. # This MODIS Python script is licensed under the terms of GNU GPL 2.
  11. # This program is free software; you can redistribute it and/or
  12. # modify it under the terms of the GNU General Public License as
  13. # published by the Free Software Foundation; either version 2 of
  14. # the License, or (at your option) any later version.
  15. # This program is distributed in the hope that it will be useful,
  16. # but WITHOUT ANY WARRANTY; without even implied warranty of
  17. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  18. # See the GNU General Public License for more details.
  19. #
  20. ##################################################################
  21. """Script to mosaic the input tiles. It is able to use MRT or GDAL as backend
  22. """
  23. import os
  24. import sys
  25. try:
  26. from pymodis import optparse_gui
  27. WXPYTHON = True
  28. except:
  29. WXPYTHON = False
  30. from pymodis import convertmodis
  31. from pymodis import convertmodis_gdal
  32. from pymodis import optparse_required
  33. from optparse import OptionGroup
  34. try:
  35. import osgeo.gdal as gdal
  36. except ImportError:
  37. try:
  38. import gdal
  39. except ImportError:
  40. raise Exception('Python GDAL library not found, please install python-gdal')
  41. ERROR = "You have to define the name of a text file containing HDF files" \
  42. " (One HDF file for line)."
  43. def main():
  44. """Main function"""
  45. # usage
  46. usage = "usage: %prog [options] hdflist_file"
  47. if 1 == len(sys.argv) and WXPYTHON:
  48. option_parser_class = optparse_gui.OptionParser
  49. else:
  50. option_parser_class = optparse_required.OptionParser
  51. parser = option_parser_class(usage=usage, description='modis_mosaic')
  52. groupR = OptionGroup(parser, 'General options')
  53. groupG = OptionGroup(parser, 'Options for GDAL')
  54. groupM = OptionGroup(parser, 'Options for MRT')
  55. # output
  56. groupR.add_option("-o", "--output", dest="output", required=True,
  57. help="the name or prefix (for VRT) of output mosaic",
  58. metavar="OUTPUT_FILE")
  59. # subset
  60. groupR.add_option("-s", "--subset", dest="subset",
  61. help="a subset of product layers. The string should"
  62. " be similar to: 1 0 [default: all layers]")
  63. # options only for GDAL
  64. groupG.add_option("-f", "--output-format", dest="output_format",
  65. metavar="OUTPUT_FORMAT", default="GTiff",
  66. help="output format supported: GTiff, HDF4Image"
  67. " [default=%default]")
  68. # groupG.add_option("-g", "--grain", dest="grain",
  69. # type="int", help="force the spatial resolution of output"
  70. # " file")
  71. # options for set VRT
  72. groupG.add_option("-v", "--vrt", dest="vrt", action="store_true",
  73. default=False, help="Create a GDAL VRT file. No other "
  74. "GDAL options have to been set")
  75. # mrt path
  76. groupM.add_option("-m", "--mrt", dest="mrt_path", type='directory',
  77. help="the path to MRT software", metavar="MRT_PATH")
  78. parser.add_option_group(groupR)
  79. parser.add_option_group(groupG)
  80. parser.add_option_group(groupM)
  81. (options, args) = parser.parse_args()
  82. # check the number of tiles
  83. if len(args) == 0 and not WXPYTHON:
  84. parser.print_help()
  85. sys.exit(1)
  86. if not args:
  87. parser.error(ERROR)
  88. else:
  89. if not isinstance(args, list):
  90. parser.error(ERROR)
  91. elif len(args) > 1:
  92. parser.error(ERROR)
  93. if not os.path.isfile(args[0]):
  94. parser.error(ERROR + '. ' + args[0] + ' does not exists')
  95. if not os.path.isfile(args[0]):
  96. parser.error("You have to define the name of a text file containing "
  97. "HDF files. (One HDF file for line)")
  98. # check is a subset it is set
  99. if not options.subset:
  100. options.subset = False
  101. else:
  102. if (options.subset.strip().startswith('(') or options.subset.strip().endswith(')')):
  103. parser.error('ERROR: The spectral string should be similar to: '
  104. '"1 0" without "(" and ")"')
  105. # if not options.grain and options.vrt:
  106. # options.grain = False
  107. # elif not options.grain and options.vrt:
  108. # parser.error("You have to define the resolution of output file. Please"
  109. # " set -g/--grain option")
  110. if options.mrt_path:
  111. modisOgg = convertmodis.createMosaic(args[0], options.output,
  112. options.mrt_path, options.subset)
  113. modisOgg.run()
  114. else:
  115. tiles = dict()
  116. dire = os.path.dirname(args[0])
  117. with open(args[0]) as f:
  118. for l in f:
  119. name = os.path.splitext(l.strip())[0]
  120. day = name.split('.')[1]
  121. if day not in tiles.keys():
  122. tiles[day] = list()
  123. if '.hdf' not in name:
  124. if dire not in l:
  125. fname = os.path.join(dire, l.strip())
  126. else:
  127. fname = l.strip()
  128. tiles[day].append(fname)
  129. for day in tiles.keys():
  130. modisOgg = convertmodis_gdal.createMosaicGDAL(tiles[day],
  131. options.subset,
  132. options.output_format)
  133. output = "{da}_{fi}".format(da=day, fi=options.output)
  134. if options.vrt:
  135. modisOgg.write_vrt(output)
  136. else:
  137. modisOgg.run(output)
  138. if __name__ == "__main__":
  139. gdal.AllRegister()
  140. argv = gdal.GeneralCmdLineProcessor(sys.argv)
  141. if argv is not None:
  142. main()