r.in.srtm.py 6.4 KB

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