r.in.srtm.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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: Import SRTM HGT files into GRASS
  46. #% keywords: raster, import
  47. #%End
  48. #%option
  49. #% key: input
  50. #% gisprompt: old_file,file,input
  51. #% type: string
  52. #% description: SRTM input tile (file without .hgt.zip extension)
  53. #% required : yes
  54. #%end
  55. #%option
  56. #% key: output
  57. #% gisprompt: new,cell,raster
  58. #% type: string
  59. #% description: 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 sys
  106. import os
  107. import shutil
  108. import atexit
  109. from grass.script import core, raster as grass
  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 = infile + ".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, zipfile))
  161. else:
  162. shutil.copyfile(hgtfile, os.path.join(tmpdir, hgtfile))
  163. #change to temporary directory
  164. os.chdir(tmpdir)
  165. in_temp = True
  166. zipfile = tile + ".hgt.zip"
  167. hgtfile = tile + ".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. if grass.run_command('r.in.gdal', input = bilfile, out = tileout) != 0:
  206. grass.fatal("Unable to import data")
  207. # nice color table
  208. grass.run_command('r.colors', map = tileout, color = 'srtm')
  209. # write cmd history:
  210. grass.raster_history(tileout)
  211. grass.message("Done: generated map " + tileout)
  212. grass.message("(Note: Holes in the data can be closed with 'r.fillnulls' using splines)")
  213. if __name__ == "__main__":
  214. options, flags = grass.parser()
  215. atexit.register(cleanup)
  216. main()