r.in.srtm.py 7.7 KB

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