Sunday, 12 February 2017

Create polygons of the extent and boundary of a given Raster in R


I want to create two polygons.




  1. One is of the rectangular extents of my raster. I know I can obtain the extent of the raster using r <- raster("band5.tif") e <- extent(r) plot(e) gives me this: enter image description here





  2. How can I create ONE polygon of the boundary of the raster as shown below?




This is what my raster looks like:raster(



Answer



Here is an example.


library(raster)
# example data
x <- raster(system.file("external/test.grd", package="raster"))


To get the rectangular extent


e <- extent(x)
# coerce to a SpatialPolygons object
p <- as(e, 'SpatialPolygons')

To get a polygon that surrounds cells that are not NA


# make all values the same. Either do
r <- x > -Inf
# or alternatively
# r <- reclassify(x, cbind(-Inf, Inf, 1))


# convert to polygons (you need to have package 'rgeos' installed for this to work)
pp <- rasterToPolygons(r, dissolve=TRUE)

# look at the results
plot(x)
plot(p, lwd=5, border='red', add=TRUE)
plot(pp, lwd=3, border='blue', add=TRUE)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...