r.in.srtm.py 7.7 KB

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