Skip to content

Instantly share code, notes, and snippets.

@jjrom
Last active November 8, 2018 08:17
Show Gist options
  • Save jjrom/5bee04de02a679a74a0c9f4f0bb35346 to your computer and use it in GitHub Desktop.
Save jjrom/5bee04de02a679a74a0c9f4f0bb35346 to your computer and use it in GitHub Desktop.
Convert 3D KML to GeoTIFF image
#!/bin/bash
#
# Convert a 3 dimension KML file into a PNG image
#
# Author : Jérôme Gasperi (https://github.com/jjrom)
# Date : 2018-11-07
#
FILENAME=__NULL__
COLORTABLE=__NULL__
SIZE=1000x1000
function showUsage {
echo ""
echo " Convert a 3 dimension KML file into a PNG image "
echo ""
echo " Usage $0 [-f] KML file"
echo ""
echo " -S | --size widthxheight output png size (default 1000x1000 pixels)"
echo " -c | --colortable use a colortable (csv file with z R G B)"
echo " -h | --help show this help"
echo ""
echo " !!! This script requires gdal to be installed !!!"
echo ""
}
# Parsing arguments
while [[ $# > 0 ]]
do
key="$1"
case $key in
-f|--file)
FILENAME="$2"
shift # past argument
;;
-S|--size)
SIZE="$2"
shift # past argument
;;
-c|--colortable)
COLORTABLE="$2"
shift # past argument
;;
-h|--help)
showUsage
exit 0
shift # past argument
;;
*)
shift # past argument
# unknown option
;;
esac
done
if [ ! -f ${FILENAME} ]; then
echo "[ERROR] Missing or invalid input KML file!"
showUsage
exit 0
fi
FILENAME_NOEXT=${FILENAME%.*}
WIDTH=`echo ${SIZE} | awk -Fx '{print $1}'`
HEIGHT=`echo ${SIZE} | awk -Fx '{print $2}'`
# Convert (X,Y,Z) KML to ESRI shapefile
ogr2ogr -f "ESRI Shapefile" ${FILENAME_NOEXT}.shp ${FILENAME_NOEXT}.kml
# Convert (X,Y,Z) shapefile to 8 bits TIFF image with color proportional to Z value
gdal_rasterize -3d -ts ${WIDTH} ${HEIGHT} ${FILENAME_NOEXT}.shp ${FILENAME_NOEXT}_unscaled.tif
# Rescale TIFF image values to [0,255]
if [ -f ${COLORTABLE} ]; then
echo "[INFO] Using color table ${COLORTABLE}"
gdaldem color-relief -nearest_color_entry ${FILENAME_NOEXT}_unscaled.tif ${COLORTABLE} ${FILENAME_NOEXT}.tif
else
gdal_translate -scale -ot Byte ${FILENAME_NOEXT}_unscaled.tif ${FILENAME_NOEXT}.tif
fi
# Clean intermediate files
rm ${FILENAME_NOEXT}.shp ${FILENAME_NOEXT}.shx ${FILENAME_NOEXT}.dbf ${FILENAME_NOEXT}.prj ${FILENAME_NOEXT}_unscaled.tif
@jjrom
Copy link
Author

jjrom commented Nov 8, 2018

Use with color table

./kml2tiff.sh -f To6O120minA.kml -c colors.csv

Examples of color tables

colors.csv

0 0 0 0
0.01 0 153 255
0.99 0 153 255
1 0 102 255
2.99 0 102 255
3 0 51 255
9.99 0 51 255
10 0 0 255

colors2.csv

0 black
0.01 red
0.99 orange
1 yellow
2.99 green
3 cyan
9.99 blue
10 white

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment