modis_convert.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. #!/usr/bin/env python
  2. # script to convert hdf file in sinusoidal projection to another format and
  3. # projection
  4. #
  5. # (c) Copyright Luca Delucchi 2012
  6. # Authors: Luca Delucchi
  7. # Email: luca dot delucchi at iasma dot it
  8. #
  9. ##################################################################
  10. #
  11. # This MODIS Python script is licensed under the terms of GNU GPL 2.
  12. # This program is free software; you can redistribute it and/or
  13. # modify it under the terms of the GNU General Public License as
  14. # published by the Free Software Foundation; either version 2 of
  15. # the License, or (at your option) any later version.
  16. # This program is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  19. # See the GNU General Public License for more details.
  20. #
  21. ##################################################################
  22. """Script to convert the input file HDF or VRT in different projection and
  23. format. It is able to use MRT or GDAL as backend
  24. """
  25. import os
  26. import sys
  27. try:
  28. from pymodis import optparse_gui
  29. WXPYTHON = True
  30. except:
  31. WXPYTHON = False
  32. from pymodis import optparse_required
  33. from pymodis import parsemodis
  34. from pymodis import convertmodis_gdal
  35. from optparse import OptionGroup
  36. try:
  37. import osgeo.gdal as gdal
  38. except ImportError:
  39. try:
  40. import gdal
  41. except ImportError:
  42. raise Exception('Python GDAL library not found, please install python-gdal')
  43. def removeBracs(stri):
  44. """Remove brackets from string"""
  45. return stri.replace(']', '').replace('[', '')
  46. def main():
  47. """Main function"""
  48. # usage
  49. usage = "usage: %prog [options] hdf_file"
  50. if 1 == len(sys.argv) and WXPYTHON:
  51. option_parser_class = optparse_gui.OptionParser
  52. else:
  53. option_parser_class = optparse_required.OptionParser
  54. parser = option_parser_class(usage=usage, description='modis_convert')
  55. groupR = OptionGroup(parser, 'General options')
  56. groupG = OptionGroup(parser, 'Options for GDAL')
  57. groupM = OptionGroup(parser, 'Options for MRT')
  58. # options used by both methos
  59. groupR.add_option("-s", "--subset", dest="subset", required=True,
  60. help="a subset of product's layers. The string should "
  61. "be similar to: ( 1 0 )")
  62. groupR.add_option("-o", "--output", dest="output", required=True,
  63. help="the prefix of output file", metavar="OUTPUT_FILE")
  64. groupR.add_option("-g", "--grain", dest="resolution", type="float",
  65. help="the spatial resolution of output file")
  66. help_resampl = "the method of resampling."
  67. help_resampl += " -- mrt methods: {res}".format(res=parsemodis.RESAM_LIST)
  68. help_resampl += " -- gdal methods: {res}".format(res=convertmodis_gdal.RESAM_GDAL)
  69. help_resampl = removeBracs(help_resampl)
  70. res_choice = parsemodis.RESAM_LIST + convertmodis_gdal.RESAM_GDAL
  71. groupR.add_option("-r", "--resampl", dest="resampling",
  72. help=help_resampl + " [default=%default]",
  73. metavar="RESAMPLING_TYPE", default='NEAREST_NEIGHBOR',
  74. type='choice', choices=res_choice)
  75. # options only for GDAL
  76. groupG.add_option("-f", "--output-format", dest="output_format",
  77. metavar="OUTPUT_FORMAT", default="GTiff",
  78. help="output format supported by GDAL [default=%default]")
  79. groupG.add_option("-e", "--epsg", dest="epsg", metavar="EPSG",
  80. help="EPSG code for the output")
  81. groupG.add_option("-w", "--wkt_file", dest="wkt", metavar="WKT",
  82. help="file or string containing projection definition"
  83. " in WKT format")
  84. groupG.add_option("-v", "--vrt", dest="vrt", action="store_true",
  85. default=False, help="Read from a GDAL VRT file.")
  86. groupG.add_option("--formats", dest="formats", action="store_true",
  87. help="print supported GDAL formats")
  88. # options only for MRT
  89. groupM.add_option("-m", "--mrt", dest="mrt_path", type='directory',
  90. help="the path to MRT software", metavar="MRT_PATH")
  91. help_datum = "the code of datum. Available: {dat}".format(dat=parsemodis.DATUM_LIST)
  92. help_datum = removeBracs(help_datum)
  93. groupM.add_option("-d", "--datum", dest="datum", default="WGS84",
  94. type='choice', choices=parsemodis.DATUM_LIST,
  95. help=help_datum + " [default=%default]")
  96. help_pt = "the output projection system. Available: {proj}".format(proj=parsemodis.PROJ_LIST)
  97. help_pt = removeBracs(help_pt)
  98. groupM.add_option("-t", "--proj_type", dest="projection_type",
  99. type='choice', metavar="PROJECTION_SYSTEM",
  100. choices=parsemodis.PROJ_LIST, action='store',
  101. help=help_pt + " [default=%default]", default='GEO')
  102. groupM.add_option("-p", "--proj_parameters", dest="projection_parameter",
  103. metavar="PROJECTION_PARAMETERS",
  104. default='( 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0'
  105. ' 0.0 0.0 0.0 0.0 )',
  106. help="a list of projection parameters, for more info "
  107. "check the 'Appendix C' of MODIS reprojection tool user"
  108. "'s manual https://lpdaac.usgs.gov/content/download"
  109. "/4831/22895/file/mrt41_usermanual_032811.pdf "
  110. "[default=%default]")
  111. groupM.add_option("-u", "--utm", dest="utm_zone", metavar="UTM_ZONE",
  112. help="the UTM zone if projection system is UTM")
  113. parser.add_option_group(groupR)
  114. parser.add_option_group(groupG)
  115. parser.add_option_group(groupM)
  116. # return options and argument
  117. (options, args) = parser.parse_args()
  118. # check the argument
  119. if len(args) == 0 and not WXPYTHON:
  120. parser.print_help()
  121. sys.exit(1)
  122. if len(args) > 1:
  123. parser.error("You have to define the name of HDF file.")
  124. if not os.path.isfile(args[0]):
  125. parser.error("You have to define the name of HDF file.")
  126. if not (options.subset.strip().startswith('(') and options.subset.strip().endswith(')')):
  127. parser.error('ERROR: The spectral string should be similar to: "( 1 0 )"')
  128. if options.mrt_path:
  129. if not options.output.endswith('.tif') and \
  130. not options.output.endswith('.hdf') and \
  131. not options.output.endswith('.hdr'):
  132. parser.error("Valid extensions for output are .hdf, .hdr, or .tif")
  133. from pymodis import convertmodis
  134. modisParse = parsemodis.parseModis(args[0])
  135. confname = modisParse.confResample(options.subset, options.resolution,
  136. options.output, options.datum,
  137. options.resampling,
  138. options.projection_type,
  139. options.utm_zone,
  140. options.projection_parameter)
  141. modisConver = convertmodis.convertModis(args[0], confname,
  142. options.mrt_path)
  143. else:
  144. modisConver = convertmodis_gdal.convertModisGDAL(args[0],
  145. options.output,
  146. options.subset,
  147. options.resolution,
  148. options.output_format,
  149. options.epsg,
  150. options.wkt,
  151. options.resampling,
  152. options.vrt)
  153. modisConver.run()
  154. if __name__ == "__main__":
  155. gdal.AllRegister()
  156. argv = gdal.GeneralCmdLineProcessor(sys.argv)
  157. if argv is not None:
  158. main()