r.in.srtm.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. #!/usr/bin/env python3
  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. import zipfile as zfile
  131. def cleanup():
  132. if not in_temp:
  133. return
  134. for ext in ['.bil', '.hdr', '.prj', '.hgt.zip']:
  135. grass.try_remove(tile + ext)
  136. os.chdir('..')
  137. grass.try_rmdir(tmpdir)
  138. def main():
  139. global tile, tmpdir, in_temp
  140. in_temp = False
  141. # to support SRTM water body
  142. swbd = False
  143. input = options['input']
  144. output = options['output']
  145. one = flags['1']
  146. # are we in LatLong location?
  147. s = grass.read_command("g.proj", flags='j')
  148. kv = grass.parse_key_val(s)
  149. if '+proj' not in kv.keys() or kv['+proj'] != 'longlat':
  150. grass.fatal(_("This module only operates in LatLong locations"))
  151. # use these from now on:
  152. infile = input
  153. while infile[-4:].lower() in ['.hgt', '.zip', '.raw']:
  154. infile = infile[:-4]
  155. (fdir, tile) = os.path.split(infile)
  156. if not output:
  157. tileout = tile
  158. else:
  159. tileout = output
  160. if '.hgt' in input:
  161. suff = '.hgt'
  162. else:
  163. suff = '.raw'
  164. swbd = True
  165. zipfile = "{im}{su}.zip".format(im=infile, su=suff)
  166. hgtfile = "{im}{su}".format(im=infile, su=suff)
  167. if os.path.isfile(zipfile):
  168. # really a ZIP file?
  169. if not zfile.is_zipfile(zipfile):
  170. grass.fatal(_("'%s' does not appear to be a valid zip file.") % zipfile)
  171. is_zip = True
  172. elif os.path.isfile(hgtfile):
  173. # try and see if it's already unzipped
  174. is_zip = False
  175. else:
  176. grass.fatal(_("File '%s' or '%s' not found") % (zipfile, hgtfile))
  177. # make a temporary directory
  178. tmpdir = grass.tempfile()
  179. grass.try_remove(tmpdir)
  180. os.mkdir(tmpdir)
  181. if is_zip:
  182. shutil.copyfile(zipfile, os.path.join(tmpdir,
  183. "{im}{su}.zip".format(im=tile,
  184. su=suff)))
  185. else:
  186. shutil.copyfile(hgtfile, os.path.join(tmpdir,
  187. "{im}{su}".format(im=tile[:7],
  188. su=suff)))
  189. # change to temporary directory
  190. os.chdir(tmpdir)
  191. in_temp = True
  192. zipfile = "{im}{su}.zip".format(im=tile, su=suff)
  193. hgtfile = "{im}{su}".format(im=tile[:7], su=suff)
  194. bilfile = tile + ".bil"
  195. if is_zip:
  196. # unzip & rename data file:
  197. grass.message(_("Extracting '%s'...") % infile)
  198. try:
  199. zf=zfile.ZipFile(zipfile)
  200. zf.extractall()
  201. except:
  202. grass.fatal(_("Unable to unzip file."))
  203. grass.message(_("Converting input file to BIL..."))
  204. os.rename(hgtfile, bilfile)
  205. north = tile[0]
  206. ll_latitude = int(tile[1:3])
  207. east = tile[3]
  208. ll_longitude = int(tile[4:7])
  209. # are we on the southern hemisphere? If yes, make LATITUDE negative.
  210. if north == "S":
  211. ll_latitude *= -1
  212. # are we west of Greenwich? If yes, make LONGITUDE negative.
  213. if east == "W":
  214. ll_longitude *= -1
  215. # Calculate Upper Left from Lower Left
  216. ulxmap = "%.1f" % ll_longitude
  217. # SRTM90 tile size is 1 deg:
  218. ulymap = "%.1f" % (ll_latitude + 1)
  219. if not one:
  220. tmpl = tmpl3sec
  221. elif swbd:
  222. grass.message(_("Attempting to import 1-arcsec SWBD data"))
  223. tmpl = swbd1sec
  224. else:
  225. grass.message(_("Attempting to import 1-arcsec data"))
  226. tmpl = tmpl1sec
  227. header = tmpl % (ulxmap, ulymap)
  228. hdrfile = tile + '.hdr'
  229. outf = open(hdrfile, 'w')
  230. outf.write(header)
  231. outf.close()
  232. # create prj file: To be precise, we would need EGS96! But who really cares...
  233. prjfile = tile + '.prj'
  234. outf = open(prjfile, 'w')
  235. outf.write(proj)
  236. outf.close()
  237. try:
  238. grass.run_command('r.in.gdal', input=bilfile, out=tileout)
  239. except:
  240. grass.fatal(_("Unable to import data"))
  241. # nice color table
  242. if not swbd:
  243. grass.run_command('r.colors', map=tileout, color='srtm')
  244. # write cmd history:
  245. grass.raster_history(tileout)
  246. grass.message(_("Done: generated map ") + tileout)
  247. grass.message(_("(Note: Holes in the data can be closed with 'r.fillnulls' using splines)"))
  248. if __name__ == "__main__":
  249. options, flags = grass.parser()
  250. atexit.register(cleanup)
  251. main()