Skip to content

Instantly share code, notes, and snippets.

@MathiasGroebe
Last active February 2, 2021 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MathiasGroebe/73c0407e3905a2bee058622053c2cf21 to your computer and use it in GitHub Desktop.
Save MathiasGroebe/73c0407e3905a2bee058622053c2cf21 to your computer and use it in GitHub Desktop.
Convert XYZ elevation data to a TIF-file using GDAL
#!/usr/bin/env python
import os
import re
import sys
import getopt
from shutil import copyfile
def main(argv):
inputFile = ''
inputRes = ''
inputEPSG = ''
try:
opts, args = getopt.getopt(argv,"h:i:r:s",["help","infile=","res=","srs="])
except getopt.GetoptError:
print('xyz2tif.py -i <input.xyz> -r <resulution> -s <EPSG:xxxx>')
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
print("xyz2tif converts a text file with values for x y z in a regular gird to a TIF-file")
print('xyz2tif.py -i <input.xyz> -r <resulution> -s <EPSG:xxxx>')
print("xyz2tif.py --infile <input.xyz> --res <resulution> --srs <EPSG:xxxx>")
sys.exit()
elif opt in ("-i", "--infile"):
inputFile = arg #filename.xyz
if inputFile == "":
print("Missing input.xyz!")
sys.exit()
elif opt in ("-r", "--res"):
inputRes = arg # 1
if inputRes == '':
print("Missing information about spatial resulution!")
sys.exit()
elif opt in ("-s", "--srs"):
inputEPSG = arg # EPSG:25833
if inputEPSG == '':
print("Missing information about the SRS!")
sys.exit()
if (inputFile != '') & (inputRes != '') & (inputEPSG != ''):
fileName = re.findall('(.+?)\.[^\.]+$', inputFile)[0]
# Create VRT-file for reading the xyz-format
f = open('xyz_dgm_reader.vrt', 'a')
f.write('<OGRVRTDataSource><OGRVRTLayer name="dgm"><SrcDataSource>dgm.csv</SrcDataSource><GeometryType>wkbPoint</GeometryType><LayerSRS>' + inputEPSG + '</LayerSRS><GeometryField encoding="PointFromColumns" x="field_1" y="field_2" z="field_3"/></OGRVRTLayer></OGRVRTDataSource>')
f.close()
print('Converting ' + inputFile + ' into TIF-file...')
copyfile(inputFile, 'dgm.csv') # Make copy of file and rename for reading in
os.system('gdal_rasterize -co compress=lzw -a_nodata -9999 -a field_3 -tr ' + inputRes + ' ' + inputRes + ' xyz_dgm_reader.vrt ' + fileName + '.tif') # Convert with help of VRT to raster
os.remove('xyz_dgm_reader.vrt') # Remove VRT
os.remove('dgm.csv') # Remove copy
else:
print("")
print("Sorry, missing some information!")
sys.exit()
if __name__ == "__main__":
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment