Problem to rasterize small polygons with rasterize function

Viewed 248

I am trying to generate a large set of binary rasters from a multi polygon shapefile. My snap raster has a large pixel, 0.5 x 0.5 degrees. I don't have major problems rasterizing de large polygons, but, for the small ones, I am writing empty raster (all 0). I am wondering if there is a tolerance parameter in rasterize function by which I will be able to assign 1 to every pixel touched by a polygon (even if the % of the polygon touched is very small).
This is the part of the code for (i in 1:length(shape)) { shape.r<-rasterize(shape[i,],snap, background=0) writeRaster(shape.r, filename = paste(shape[i,]$binomial, sep=""), format = "GTiff", overwrite = T) }

Thanks! Javier.

1 Answers

Here is some example data

f <- system.file("ex/lux.shp", package="terra")
v <- vect(f)
x <- lapply(1:nrow(v), \(i)rescale(v[i,], 0.2))
vv <- vect(x)
r <- rast(v, ncols=10, nrows=10)
b <- as.lines(r)

The standard rasterize method misses a lot of the polygons if they are small relative to the cell size.

x <- rasterize(vv, r, "ID_2")
plot(x)
lines(b, col="light gray")
lines(vv)

enter image description here

The argument touches=TRUE can help in this case

xx <- rasterize(vv, r, "ID_2", touches=TRUE)
plot(xx)
lines(b, col="light gray")
lines(vv)

enter image description here

But if they polygons are even smaller, they could still be missed. One approach to deal with that is to also rasterize the centroids of the polygons (rasterize probably should have an argument to do this automatically).

cnt <- centroids(vv)
# leaving out touches=T otherwise the example is not interesting
# with these data
x <- rasterize(vv, r, "ID_2")
y <- rasterize(cnt, r, "ID_2")
z <- cover(x, y)

plot(z)
lines(b, col="light gray")
lines(vv)

enter image description here

You can also consider using

x <- rasterize(vv, r, cover=TRUE)
x <- x > 0    
Related