polygon2mask {tigers} | R Documentation |
Convert Polygon to a Raster Mask
Description
Takes a polygon and returns a matrix with a mask that can be input into a raster.
Usage
polygon2mask(XY, extent = NULL, k = 360,
value = 1L, backgrd = 0L)
Arguments
XY |
A two-column matrix giving the coordinates of a polygon. |
extent |
a vector with four numeric values giving the extent of the raster. By default, values are determined to minimally cover the polygon. |
k |
an integer value giving the number of pixels per unit (i.e., the inverse of the resolution of the raster). The resolution is the same in both directions. |
value |
the value given to the pixels inside the polygon (converted to integer). |
backgrd |
idem for the pixels outside the polygon. |
Details
The mask is returned as a matrix which is filled rowwise (in agreement
with the convention used in rasters) and can be input into functions
in terra (e.g., rast()
).
polygon2mask
does basically the same operation than
terra::rasterize()
but is faster and can produce a vector for
masking raster data.
The output matrix is actually row-filled (unlike most matrices in R
which are column-filled). It should be transposed before passed to
terra::rast()
, or its dim
attribute can be ignored if
used as a mask to a rasted (which is also usually row-filled).
Value
a matrix stored as integers; the dimensions of this matrix give the size of the raster.
Note
The code is still in development.
Author(s)
Emmanuel Paradis
References
Nievergelt, J. and Preparata, F. P. (1982) Plane-sweep algorithms for intersecting geometric figures. Communications of the ACM, 25, 739–747. <doi:10.1145/358656.358681>.
Examples
## from ?chullPolygon:
XY <- rbind(c(0, 0),
c(1, 0),
c(.25, .25),
c(.5, .5),
c(1.2, .8),
c(1, .78),
c(0, 1))
layout(matrix(1:9, 3, 3, TRUE))
k <- 2
for (i in 1:9) {
msk <- polygon2mask(XY, k = k)
d <- dim(msk)
image(1:d[1], 1:d[2], msk)
dm <- paste(d, collapse = "x")
title(paste("k =", k, ", dim =", dm))
k <- k * 2
}
layout(1)