Skip to content

Instantly share code, notes, and snippets.

@psaia
Created September 15, 2015 20:52
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save psaia/06ebe6da964f0e39a530 to your computer and use it in GitHub Desktop.
Save psaia/06ebe6da964f0e39a530 to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# Requires:
# - gdal_sieve.py
# - ogr2ogr (GDAL)
# - topojson (node.js)
# Grab the relative directory for source file.
SRC_DIR=`dirname $0`
# Which raster to compress.
ORG_FILE="$SRC_DIR/raw/anthromes/$1/anthro2_a$1.tif"
# Final output file.
OUTPUT_FILE="$SRC_DIR/processed/anthrome-$1.json"
echo "Processing $ORG_FILE."
# Where to output the new file.
TMP_DIR=./tmp
# The amount of times the file should be passed over.
ITERATIONS=3
# Threshold for each iteration.
THRESHOLD=40
# TopoJSON area threshold for simplification.
TOPO_COMPRESSION=0.000005
# Setup internal vars.
_CUR=$THRESHOLD
_COMPRESSION=$(($ITERATIONS * $THRESHOLD))
rm -rf $TMP_DIR
mkdir -p $TMP_DIR
# Start sieve passes.
gdal_sieve.py -st $THRESHOLD -4 $ORG_FILE $TMP_DIR/output-"$THRESHOLD".tiff
while [ $_CUR -le $_COMPRESSION ]; do
let _PREV=$_CUR
let _CUR=$_CUR+$THRESHOLD
echo "Compressing output-$_PREV.tiff into $_CUR.tiff"
gdal_sieve.py -st $THRESHOLD -4 "$TMP_DIR/output-$_PREV.tiff" \
"$TMP_DIR/output-$_CUR.tiff"
rm "$TMP_DIR/output-$_PREV.tiff"
done
# Raster to vector.
gdal_polygonize.py $TMP_DIR/output-"$_CUR".tiff \
-f "ESRI Shapefile" $TMP_DIR vector n
# Change shapefile to geojson without the 0 layer, which is water.
ogr2ogr -f "GeoJSON" -where "n != 0" "$TMP_DIR/geojson.json" $TMP_DIR/vector.shp
# Convert to compressed TopoJSON.
topojson -o $OUTPUT_FILE \
--no-stitch-poles \
-s $TOPO_COMPRESSION \
-p -- "$TMP_DIR/geojson.json"
# Clean up.
rm -rf $TMP_DIR
@sdkjoshi
Copy link

Thank you for this code. Would you create one that converts geojson to geotiff?

@coloredlambda
Copy link

coloredlambda commented Apr 4, 2020

The topojson on line 58 does not work anymore. Change it to geo2topo
You can get the executable using npm
npm i -g topojson

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