Skip to content

Instantly share code, notes, and snippets.

@JoshOBrien
JoshOBrien / gRasterize.R
Last active October 25, 2021 19:22
gRasterize -- Fast rasterization of spatial objects using gdalUtilities::gdal_rasterize
##' Rasterize \code{Spatial*} objects using gdal_rasterize.
##'
##' For a 1000-by-1000 raster, \code{gRasterize} is more than 6 times
##' faster than \code{raster::rasterize}. For a 2000-by-2000 raster,
##' it is almost 12 times faster (6 seconds vs. 70 seconds on my
##' Windows laptop).
##'
##' I've modeled \code{gRasterize} arguments and behavior on that of
##' \code{\link[raster]{rasterize}}. Like\code{rasterize},it takes a
##' \code{filename=} argument which defaults to \code{""} in which
polygonizer <- function(x, outshape=NULL, gdalformat = 'ESRI Shapefile',
pypath=NULL, readpoly=TRUE, quietish=TRUE) {
# x: an R Raster layer, or the file path to a raster file recognised by GDAL
# outshape: the path to the output shapefile (if NULL, a temporary file will be created)
# gdalformat: the desired OGR vector format
# pypath: the path to gdal_polygonize.py (if NULL, an attempt will be made to determine the location
# readpoly: should the polygon shapefile be read back into R, and returned by this function? (logical)
# quietish: should (some) messages be suppressed? (logical)
if (isTRUE(readpoly)) require(rgdal)
if (is.null(pypath)) {