Created
December 3, 2015 00:24
-
-
Save TaylorMutch/4aba0d50bc4cf03a06b2 to your computer and use it in GitHub Desktop.
Convert from simple binary format to ArcAscii - based on https://gist.github.com/nikmolnar/284b5541bfc54946a24b
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__author__ = 'Taylor' | |
''' | |
Convert binary format to ArcAscii Format - adapted from https://gist.github.com/nikmolnar/284b5541bfc54946a24b | |
''' | |
import os, struct, sys, math, requests | |
server = 'your/terrain/server/here' # Ask for the URL if you want to try it out. | |
def main(): | |
if len(sys.argv) < 2: | |
print('Usage: get_ascii.py <terrainName>.asc') | |
sys.exit(-1) | |
output_path = sys.argv[1] | |
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) | |
lat1 = float(input('South: ')) | |
lat2 = float(input('North: ')) | |
lng1 = float(input('East: ')) | |
lng2 = float(input('West: ')) | |
width = int(input('Number of segments: ')) | |
height = int(input('Number of latitude segments (-1 for equal aspect ratio): ')) | |
if (height == -1): | |
payload = {'lat1': str(lat1), | |
'lat2': str(lat2), | |
'lng1': str(lng1), | |
'lng2': str(lng2), | |
'numlngs': str(width)} | |
else: | |
payload = {'lat1': str(lat1), | |
'lat2': str(lat2), | |
'lng1': str(lng1), | |
'lng2': str(lng2), | |
'numlats': str(height), | |
'numlngs': str(width)} | |
try: | |
r = requests.get(server, params=payload) | |
print(r.content) | |
print('Request successful, writing to ' + output_path + '\n') | |
except requests.HTTPError: | |
print('Request failed... a team of highly trained monkeys is on its way!') | |
sys.exit(-1) | |
if (height == -1): # Get the correct number of latitudes from the server | |
form_feed = b'\x0c' | |
index = 0 | |
myChar = b'' | |
while myChar != form_feed: | |
myChar = r.content[index:index+1] | |
if myChar == form_feed: | |
break | |
index +=1 | |
height = int(r.content[:index].decode('ascii').split()[5]) # this is the right position for height | |
with open(output_path, 'w') as f_out: | |
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)) | |
index = 0 | |
for i in range(1, height + 1): | |
index = len(r.content) - i*4*width # floats are 4 bytes long | |
floats = struct.unpack('f' * width, r.content[index: index + 4*width]) | |
line = (str(x) for x in floats) | |
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