Clipping Rasters with GeoJSON Polygons

A recent side project we’ve been working on at SNAP requires clipping data from a user selected polygon.  Plenty of people are already using the gdalwarp utilities for data clipping, but using GeoJSON seems to be a bit less popular.  In our case, since the polygon is being passed over the web, JSON seemed like a natural format.  And since the GeoJSON specification is designed specifically for the job, it seemed like a natural solution.

Here is the area we want to clip:

polygon

In this case, the GeoJSON file itself is being produced by a series of clicks by the user in a Google Maps interface, and then written to a temporary file.  Here’s an example of a simple file passing a triangle centered over Alaska:

{ “type”: “FeatureCollection”,
“features”: [ {
“type”: “Feature”,
“properties”: { “prop0”: “value0” },
“id”: 0,
“geometry”: {
“type”: “Polygon”,
“coordinates”: [ [ [ -156.97265625, 62.99515845212052 ],
[ -143.525390625, 62.99515845212052 ],
[ -150.29296875, 67.90861918215302 ] ] ]
} } ] }

The GeoJSON file can be loaded into QGIS for a quick check:

qgis

With a valid GeoJSON file (validator available at geojsonlint.com, the next step is to run clip together with a gdalwarp command.  The basic idea is this:

gdalwarp -of GTiff -crop_to_cutline -cutline polygon.json input.tif output.tif

For our specific case, the actual command is this:

gdalwarp -dstnodata 255 -co COMPRESS=DEFLATE -of GTiff -r lanczos -crop_to_cutline -cutline polygon.json input.tif clipped.tif

And now we have the end product (with a color style applied to our vegetation map):

endproduct

There are a few key points worth noting.  In order to clip data using a GeoJSON, the “id” field is absolutely necessary (even if it’s optional to the GeoJSON file itself).  Without it, the crop_to_cutline will still clip to the extent of the polygon, but will essentially return null data for the entire extent.  The crop_to_cutline is a *relatively* newer GDAL feature, available in gdal >= 1.8.0.

Everything else is just extras.

Combined with a web interface for polygon selection, server side clipping can be done in this way with as little as a one line bash script, a server side raster database, or any other implementation of choice, and GeoJSON is a great, simple, and compact alternative to other options.

This entry was posted by Alec Bennett.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: