Skip to content
Prev 17442 / 29559 Next

R version of gdal_polygonize.py

Hi Jonathan,

With rasterToPolygons, the dissolve = T argument should do what you
want in terms of merging common value polygons, provided you have
rgeos installed.

I also use the a system call to gdal_polygonize.py, which seems to
help for larger polygons.

runGdalPolygonize <- function(inraster, outshape, attname, readin =
TRUE, gdalformat = "ESRI Shapefile") {
# Runs gdal_polygonize.py to create polygons from raster (with limited
options at present)
# Args:
#   inraster: The name of a raster object referring to a permanent,
GDAL-readable raster
#   outshape: The name of the desired output polygon file
#   attname: The name for the column in the output attribute table
#   gdalformat: Defaults to ESRI shapefile at present
#   readin: Option specifies whether result is read into an R object
or not, defaults to TRUE. Set to FALSE
#     (and don't assign to an object) and it will just write to disk
(useful for when polygons are very large)
# Returns:
#   Polygon file, read back in to an R object
# Notes:
#   This needs to be run within the directory containing the raster file

  py.c <- "python2.7
/Library/Frameworks/GDAL.framework/Versions/1.8/Programs/gdal_polygonize.py"
  rast.nm <- unlist(strsplit(inraster at file@name,
"/"))[length(unlist(strsplit(inraster at file@name, "/")))]
  full.c <- paste(py.c, rast.nm, "-f", paste("'", gdalformat, "'", sep = ""),
                  paste(outshape, ".shp", sep = ""), outshape, attname)
  system(full.c, intern = TRUE)
  if(readin == TRUE) {
    shp <- readOGR(dsn = paste(outshape, ".shp", sep = ""), layer = outshape)
    return(shp)
  }
}

Cheers, Lyndon
On Tue, Feb 12, 2013 at 9:40 AM, Jonathan Greenberg <jgrn at illinois.edu> wrote: