r.in.srtm.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. def cleanup():
  111. if not in_temp:
  112. return
  113. for ext in ['.bil', '.hdr', '.prj', '.hgt.zip']:
  114. grass.try_remove(tile + ext)
  115. os.chdir('..')
  116. grass.try_rmdir(tmpdir)
  117. def main():
  118. global tile, tmpdir, in_temp
  119. in_temp = False
  120. input = options['input']
  121. output = options['output']
  122. one = flags['1']
  123. #are we in LatLong location?
  124. s = grass.read_command("g.proj", flags='j')
  125. kv = grass.parse_key_val(s)
  126. if kv['+proj'] != 'longlat':
  127. grass.fatal(_("This module only operates in LatLong locations"))
  128. # use these from now on:
  129. infile = input
  130. while infile[-4:].lower() in ['.hgt', '.zip']:
  131. infile = infile[:-4]
  132. (fdir, tile) = os.path.split(infile)
  133. if not output:
  134. tileout = tile
  135. else:
  136. tileout = output
  137. zipfile = infile + ".hgt.zip"
  138. hgtfile = os.path.join(fdir, tile[:7] + ".hgt")
  139. if os.path.isfile(zipfile):
  140. #### check if we have unzip
  141. if not grass.find_program('unzip'):
  142. grass.fatal(_('The "unzip" program is required, please install it first'))
  143. # really a ZIP file?
  144. # make it quiet in a safe way (just in case -qq isn't portable)
  145. tenv = os.environ.copy()
  146. tenv['UNZIP'] = '-qq'
  147. if grass.call(['unzip', '-t', zipfile], env = tenv) != 0:
  148. grass.fatal(_("'%s' does not appear to be a valid zip file.") % zipfile)
  149. is_zip = True
  150. elif os.path.isfile(hgtfile):
  151. # try and see if it's already unzipped
  152. is_zip = False
  153. else:
  154. grass.fatal(_("File '%s' or '%s' not found") % (zipfile, hgtfile))
  155. #make a temporary directory
  156. tmpdir = grass.tempfile()
  157. grass.try_remove(tmpdir)
  158. os.mkdir(tmpdir)
  159. if is_zip:
  160. shutil.copyfile(zipfile, os.path.join(tmpdir, tile + ".hgt.zip"))
  161. else:
  162. shutil.copyfile(hgtfile, os.path.join(tmpdir, tile + ".hgt"))
  163. #change to temporary directory
  164. os.chdir(tmpdir)
  165. in_temp = True
  166. zipfile = tile + ".hgt.zip"
  167. hgtfile = tile[:7] + ".hgt"
  168. bilfile = tile + ".bil"
  169. if is_zip:
  170. #unzip & rename data file:
  171. grass.message(_("Extracting '%s'...") % infile)
  172. if grass.call(['unzip', zipfile], env = tenv) != 0:
  173. grass.fatal(_("Unable to unzip file."))
  174. grass.message(_("Converting input file to BIL..."))
  175. os.rename(hgtfile, bilfile)
  176. north = tile[0]
  177. ll_latitude = int(tile[1:3])
  178. east = tile[3]
  179. ll_longitude = int(tile[4:7])
  180. # are we on the southern hemisphere? If yes, make LATITUDE negative.
  181. if north == "S":
  182. ll_latitude *= -1
  183. # are we west of Greenwich? If yes, make LONGITUDE negative.
  184. if east == "W":
  185. ll_longitude *= -1
  186. # Calculate Upper Left from Lower Left
  187. ulxmap = "%.1f" % ll_longitude
  188. # SRTM90 tile size is 1 deg:
  189. ulymap = "%.1f" % (ll_latitude + 1)
  190. if not one:
  191. tmpl = tmpl3sec
  192. else:
  193. grass.message(_("Attempting to import 1-arcsec data."))
  194. tmpl = tmpl1sec
  195. header = tmpl % (ulxmap, ulymap)
  196. hdrfile = tile + '.hdr'
  197. outf = file(hdrfile, 'w')
  198. outf.write(header)
  199. outf.close()
  200. #create prj file: To be precise, we would need EGS96! But who really cares...
  201. prjfile = tile + '.prj'
  202. outf = file(prjfile, 'w')
  203. outf.write(proj)
  204. outf.close()
  205. try:
  206. grass.run_command('r.in.gdal', input=bilfile, out=tileout)
  207. except:
  208. grass.fatal(_("Unable to import data"))
  209. # nice color table
  210. grass.run_command('r.colors', map = tileout, color = 'srtm')
  211. # write cmd history:
  212. grass.raster_history(tileout)
  213. grass.message(_("Done: generated map ") + tileout)
  214. grass.message(_("(Note: Holes in the data can be closed with 'r.fillnulls' using splines)"))
  215. if __name__ == "__main__":
  216. options, flags = grass.parser()
  217. atexit.register(cleanup)
  218. main()