Created
January 2, 2020 23:27
-
-
Save LarsSchy/c1be96fa03f7dc11df4247be033e2705 to your computer and use it in GitHub Desktop.
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
#!/bin/bash | |
# | |
# palette_reclass.sh | |
# Lars Schylberg, 2020-01-03 | |
# | |
# example how to reclass a tif palette image with gdal_calc | |
# and some glue with awk and sed | |
# | |
# land 59,89,95,255 and / or 60,89,96,255 ---> 1 | |
# sea 109,178,200,255 / 138,193,212,255 and 161,205,220,255. --> 0 | |
INPUT_FILE=your_file.tif | |
CALC_RULE=$(gdalinfo ${INPUT_FILE} | sed -e '1,/Color Table/d' | \ | |
awk -F: '{if ($2==" 59,89,95,255") {printf "1*(A==%d)+", $1} | |
else if ($2==" 60,89,96,255") {printf "1*(A==%d)+", $1} | |
else if ($2==" 109,178,200,255") {printf "0*(A==%d)+", $1} | |
else if ($2==" 138,193,212,255") {printf "0*(A==%d)+", $1} | |
else if ($2==" 161,205,220,255") {printf "0*(A==%d)+", $1};}' | \ | |
sed '$ s/.$//') | |
# echo $CALC_RULE | |
# Result with your example: 1*(A==0)+0*(A==1)+0*(A==2) | |
gdal_calc.py -A ${INPUT_FILE} \ | |
--outfile=output.tif \ | |
--calc="${CALC_RULE}" | |
# create a vrt for the new processed file | |
gdal_translate -of VRT output.tif output.vrt | |
# make a new vrt color table, just the first two values are used | |
cat <<EOF > color_table.txt | |
<ColorTable> | |
<Entry c1="0" c2="0" c3="0" c4="255" /> | |
<Entry c1="255" c2="255" c3="255" c4="255" /> | |
EOF | |
for i in {1..254} | |
do | |
echo " <Entry c1="255" c2="255" c3="255" c4="255" />" >> color_table.txt | |
done | |
echo " </ColorTable>" >> color_table.txt | |
# insert the new color table in the vrt image | |
# after the row that contains the word Gray | |
sed -i -e '/Gray/r color_table.txt' output.vrt | |
# change color interpretation from Gray to Palette | |
sed -i -e 's/Gray/Palette/' output.vrt | |
# make a real tif image again from the vrt | |
gdal_translate \ | |
-co COMPRESS=PACKBITS \ | |
-co INTERLEAVE=BAND \ | |
output.vrt \ | |
final_output.tif | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment