r.in.srtm.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. #!/usr/bin/env python
  2. #
  3. ############################################################################
  4. #
  5. # MODULE: r_in_aster.py
  6. # AUTHOR(S): Markus Neteler 11/2003 neteler AT itc it
  7. # Hamish Bowman
  8. # Glynn Clements
  9. # PURPOSE: import of SRTM hgt files into GRASS
  10. #
  11. # COPYRIGHT: (C) 2004, 2006 by the GRASS Development Team
  12. #
  13. # This program is free software under the GNU General Public
  14. # License (>=v2). Read the file COPYING that comes with GRASS
  15. # for details.
  16. #
  17. # Dec 2004: merged with srtm_generate_hdr.sh (M. Neteler)
  18. # corrections and refinement (W. Kyngesburye)
  19. # Aug 2004: modified to accept files from other directories
  20. # (by H. Bowman)
  21. # June 2005: added flag to read in US 1-arcsec tiles (H. Bowman)
  22. # April 2006: links updated from ftp://e0dps01u.ecs.nasa.gov/srtm/
  23. # to current links below
  24. # October 2008: Converted to Python by Glynn Clements
  25. #########################
  26. # Derived from:
  27. # ftp://e0srp01u.ecs.nasa.gov/srtm/version1/Documentation/Notes_for_ARCInfo_users.txt
  28. # (note: document was updated silently end of 2003)
  29. #
  30. # ftp://e0srp01u.ecs.nasa.gov/srtm/version1/Documentation/SRTM_Topo.txt
  31. # "3.0 Data Formats
  32. # [...]
  33. # To be more exact, these coordinates refer to the geometric center of
  34. # the lower left pixel, which in the case of SRTM-1 data will be about
  35. # 30 meters in extent."
  36. #
  37. #- SRTM 90 Tiles are 1 degree by 1 degree
  38. #- SRTM filename coordinates are said to be the *center* of the LL pixel.
  39. # N51E10 -> lower left cell center
  40. #
  41. #- BIL uses *center* of the UL (!) pixel:
  42. # http://downloads.esri.com/support/whitepapers/other_/eximgav.pdf
  43. #
  44. #- GDAL uses *corners* of pixels for its coordinates.
  45. #
  46. # NOTE: Even, if small difference: SRTM is referenced to EGM96, not WGS84 ellps
  47. # http://earth-info.nga.mil/GandG/wgs84/gravitymod/egm96/intpt.html
  48. #
  49. #########################
  50. #%Module
  51. #% description: Imports SRTM HGT files into raster map.
  52. #% keyword: raster
  53. #% keyword: import
  54. #%End
  55. #%option G_OPT_F_INPUT
  56. #% description: Name of SRTM input tile (file without .hgt.zip extension)
  57. #%end
  58. #%option G_OPT_R_OUTPUT
  59. #% description: Name for output raster map (default: input tile)
  60. #% required : no
  61. #%end
  62. #%flag
  63. #% key: 1
  64. #% description: Input is a 1-arcsec tile (default: 3-arcsec)
  65. #%end
  66. tmpl1sec = """BYTEORDER M
  67. LAYOUT BIL
  68. NROWS 3601
  69. NCOLS 3601
  70. NBANDS 1
  71. NBITS 16
  72. BANDROWBYTES 7202
  73. TOTALROWBYTES 7202
  74. BANDGAPBYTES 0
  75. PIXELTYPE SIGNEDINT
  76. NODATA -32768
  77. ULXMAP %s
  78. ULYMAP %s
  79. XDIM 0.000277777777777778
  80. YDIM 0.000277777777777778
  81. """
  82. tmpl3sec = """BYTEORDER M
  83. LAYOUT BIL
  84. NROWS 1201
  85. NCOLS 1201
  86. NBANDS 1
  87. NBITS 16
  88. BANDROWBYTES 2402
  89. TOTALROWBYTES 2402
  90. BANDGAPBYTES 0
  91. PIXELTYPE SIGNEDINT
  92. NODATA -32768
  93. ULXMAP %s
  94. ULYMAP %s
  95. XDIM 0.000833333333333
  96. YDIM 0.000833333333333
  97. """
  98. proj = ''.join([
  99. 'GEOGCS[',
  100. '"wgs84",',
  101. 'DATUM["WGS_1984",SPHEROID["wgs84",6378137,298.257223563],TOWGS84[0.000000,0.000000,0.000000]],',
  102. 'PRIMEM["Greenwich",0],',
  103. 'UNIT["degree",0.0174532925199433]',
  104. ']'])
  105. import os
  106. import shutil
  107. import atexit
  108. import grass.script as grass
  109. from grass.exceptions import CalledModuleError
  110. # i18N
  111. import gettext
  112. gettext.install('grassmods', os.path.join(os.getenv("GISBASE"), 'locale'))
  113. def cleanup():
  114. if not in_temp:
  115. return
  116. for ext in ['.bil', '.hdr', '.prj', '.hgt.zip']:
  117. grass.try_remove(tile + ext)
  118. os.chdir('..')
  119. grass.try_rmdir(tmpdir)
  120. def main():
  121. global tile, tmpdir, in_temp
  122. in_temp = False
  123. input = options['input']
  124. output = options['output']
  125. one = flags['1']
  126. # are we in LatLong location?
  127. s = grass.read_command("g.proj", flags='j')
  128. kv = grass.parse_key_val(s)
  129. if kv['+proj'] != 'longlat':
  130. grass.fatal(_("This module only operates in LatLong locations"))
  131. # use these from now on:
  132. infile = input
  133. while infile[-4:].lower() in ['.hgt', '.zip']:
  134. infile = infile[:-4]
  135. (fdir, tile) = os.path.split(infile)
  136. if not output:
  137. tileout = tile
  138. else:
  139. tileout = output
  140. zipfile = infile + ".hgt.zip"
  141. hgtfile = os.path.join(fdir, tile[:7] + ".hgt")
  142. if os.path.isfile(zipfile):
  143. # check if we have unzip
  144. if not grass.find_program('unzip'):
  145. grass.fatal(_('The "unzip" program is required, please install it first'))
  146. # really a ZIP file?
  147. # make it quiet in a safe way (just in case -qq isn't portable)
  148. tenv = os.environ.copy()
  149. tenv['UNZIP'] = '-qq'
  150. if grass.call(['unzip', '-t', zipfile], env=tenv) != 0:
  151. grass.fatal(_("'%s' does not appear to be a valid zip file.") % zipfile)
  152. is_zip = True
  153. elif os.path.isfile(hgtfile):
  154. # try and see if it's already unzipped
  155. is_zip = False
  156. else:
  157. grass.fatal(_("File '%s' or '%s' not found") % (zipfile, hgtfile))
  158. # make a temporary directory
  159. tmpdir = grass.tempfile()
  160. grass.try_remove(tmpdir)
  161. os.mkdir(tmpdir)
  162. if is_zip:
  163. shutil.copyfile(zipfile, os.path.join(tmpdir, tile + ".hgt.zip"))
  164. else:
  165. shutil.copyfile(hgtfile, os.path.join(tmpdir, tile + ".hgt"))
  166. # change to temporary directory
  167. os.chdir(tmpdir)
  168. in_temp = True
  169. zipfile = tile + ".hgt.zip"
  170. hgtfile = tile[:7] + ".hgt"
  171. bilfile = tile + ".bil"
  172. if is_zip:
  173. # unzip & rename data file:
  174. grass.message(_("Extracting '%s'...") % infile)
  175. if grass.call(['unzip', zipfile], env=tenv) != 0:
  176. grass.fatal(_("Unable to unzip file."))
  177. grass.message(_("Converting input file to BIL..."))
  178. os.rename(hgtfile, bilfile)
  179. north = tile[0]
  180. ll_latitude = int(tile[1:3])
  181. east = tile[3]
  182. ll_longitude = int(tile[4:7])
  183. # are we on the southern hemisphere? If yes, make LATITUDE negative.
  184. if north == "S":
  185. ll_latitude *= -1
  186. # are we west of Greenwich? If yes, make LONGITUDE negative.
  187. if east == "W":
  188. ll_longitude *= -1
  189. # Calculate Upper Left from Lower Left
  190. ulxmap = "%.1f" % ll_longitude
  191. # SRTM90 tile size is 1 deg:
  192. ulymap = "%.1f" % (ll_latitude + 1)
  193. if not one:
  194. tmpl = tmpl3sec
  195. else:
  196. grass.message(_("Attempting to import 1-arcsec data."))
  197. tmpl = tmpl1sec
  198. header = tmpl % (ulxmap, ulymap)
  199. hdrfile = tile + '.hdr'
  200. outf = file(hdrfile, 'w')
  201. outf.write(header)
  202. outf.close()
  203. # create prj file: To be precise, we would need EGS96! But who really cares...
  204. prjfile = tile + '.prj'
  205. outf = file(prjfile, 'w')
  206. outf.write(proj)
  207. outf.close()
  208. try:
  209. grass.run_command('r.in.gdal', input=bilfile, out=tileout)
  210. except:
  211. grass.fatal(_("Unable to import data"))
  212. # nice color table
  213. grass.run_command('r.colors', map=tileout, color='srtm')
  214. # write cmd history:
  215. grass.raster_history(tileout)
  216. grass.message(_("Done: generated map ") + tileout)
  217. grass.message(_("(Note: Holes in the data can be closed with 'r.fillnulls' using splines)"))
  218. if __name__ == "__main__":
  219. options, flags = grass.parser()
  220. atexit.register(cleanup)
  221. main()