Created
February 20, 2020 21:17
-
-
Save capooti/019dd6b5959052cdfc3d8f7de117bf84 to your computer and use it in GitHub Desktop.
Generates a geotiff file from a kml with groundoverlays
This file contains hidden or 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
import argparse | |
import os | |
import xmltodict | |
def do_kml2tiff_conversion(input_path, input_kml, output_path, output_tif): | |
with open(input_kml) as f: | |
doc = xmltodict.parse(f.read()) | |
out_img_names = [] | |
gos = doc['kml']['Folder']['GroundOverlay'] | |
if type(gos) != list: | |
gos = [gos, ] | |
for go in gos: | |
img_name = go['Icon']['href'] | |
north = go['LatLonBox']['north'] | |
south = go['LatLonBox']['south'] | |
east = go['LatLonBox']['east'] | |
west = go['LatLonBox']['west'] | |
print(img_name, north, south, east, west) | |
# 1. gdal_translate to georeference the rasters | |
# gdal_translate -of GTiff -a_ullr 31.00 3.99917 32.00 3.00 -a_srs EPSG:4326 5.png 5.tiff | |
in_img_name = input_path + img_name | |
out_img_name = output_path + img_name.replace('.png', '.tiff') | |
out_img_names.append(out_img_name) | |
gdal_translate_command = f'gdal_translate -of GTiff -a_ullr {west} {north} {east} {south} -a_srs EPSG:4326 {in_img_name} {out_img_name}' | |
os.system(gdal_translate_command) | |
# 2. gdal_merge.py to merge the rasters in a single file | |
# gdal_merge.py -o merged.tiff -of GTiff 0.tiff 1.tiff 2.tiff 3.tiff 4.tiff 5.tiff | |
gdal_merge_command = f'gdal_merge.py -o {output_path}{output_tif} -of GTiff ' + ' '.join(out_img_names) | |
print(gdal_merge_command) | |
os.system(gdal_merge_command) | |
print('Export completed!') | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-s', '--input-path', required=True, dest='input_path') | |
parser.add_argument('-d', '--output-path', required=True, dest='output_path') | |
parser.add_argument('-n', '--output-img-name', required=True, dest='output_img_name') | |
parser.add_argument('-k', '--input-kml', required=True, dest='input_kml') | |
params = parser.parse_args() | |
# sample usage: | |
# python kml2tiff.py -s U2/ -d out/ -n U2 -k U2/doc.kml | |
do_kml2tiff_conversion(params.input_path, params.input_kml, params.output_path, params.output_img_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment