Skip to content

Instantly share code, notes, and snippets.

@nikmolnar
Created June 3, 2015 17:43
Show Gist options
  • Save nikmolnar/284b5541bfc54946a24b to your computer and use it in GitHub Desktop.
Save nikmolnar/284b5541bfc54946a24b to your computer and use it in GitHub Desktop.
This script converts from a simple binary elevation format to ArcASCII.
"""
This script converts from a simple binary elevation format to ArcASCII. The format of the binary file is:
Offset Type Description
-----------------------------
0 uint Grid width
4 uint Grid height
8 float* Elevation values as floats in row-major order from lower-left to upper-right.
"""
import os
import struct
import sys
# input() in Py2 processes numbers only, so map to raw_input
if sys.version_info[0] < 3:
input = raw_input
def main():
if len(sys.argv) < 3:
print('Usage: convert_grid.py <input grid> <output grid>')
sys.exit(-1)
input_path, output_path = sys.argv[1:3]
if os.path.exists(output_path):
overwrite_message = '{0} already exists. Overwrite? [y/n] '.format(output_path)
if not input(overwrite_message).lower().startswith('y'):
sys.exit(-1)
with open(output_path, 'w') as f_out:
with open(input_path, 'rb') as f_in:
width, height = struct.unpack('II', f_in.read(8))
f_in.seek(0, os.SEEK_END)
assert f_in.tell() == width * height * 4 + 8
header = [
'ncols {0}'.format(width),
'nrows {0}'.format(height),
'xllcorner 0.0',
'yllcorner 0.0',
'cellsize 1.0',
'NODATA_value -9999',
''
]
f_out.write('\n'.join(header))
# The binary format orders rows from bottom to top, while the ArcASCII format orders top to bottom.
# So we'll read from the end of the binary file backwards
for i in range(1, height + 1):
f_in.seek(-i * width * 4, os.SEEK_END)
row = struct.unpack('f' * width, f_in.read(width * 4))
line = (str(x) for x in row)
f_out.write(' '.join(line) + '\n')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment