Fastest way to mask raster using points

♀尐吖头ヾ 提交于 2020-05-16 22:01:15

问题


I have a very large rasterbrick and some coordinates held in a different object. I wish to use the points as a mask, returning NA for all cells except where my points are located (for my particular application I need to preserve the extent, resolution and origin of the input rasterbrick).

I can accomplish this with the following:

library(raster)
library(tidyverse)
library(sf)

# Load a rasterbrick
b <- brick(system.file("external/rlogo.grd", package="raster"))

# Create some random points as test points for masking
pts<-as_tibble(rasterToPoints(b[[1]])) %>% 
  select(x, y) %>% 
  sample_n(15, replace = TRUE)

plot(b[[1]])
points(pts)

# Convert points to SpatialPoints so they can be passed to `mask`
pts <- st_as_sf(x = pts, coords = c("x", "y"),
                crs = crs(b))

# Mask stack using pts
xx<-raster::mask(b, pts)
plot(xx)

In this example, the code executes very quickly but when scaling this up, it can take a long time to run. What would be a more efficient way of doing this for a large, multi-layer rasterbrick? For a sense of scale, my rasterbrick's are360, 720, 259200, 3653 (nrow, ncol, ncell, nlayers)` so it would be great to speed things along.


回答1:


That is a lot of layers.

Your code (with some simplification)

library(raster)
b <- brick(system.file("external/rlogo.grd", package="raster"))
set.seed(1)
pts <- sampleRandom(b, 10, sp=TRUE)
xx <- raster::mask(b, pts)

Two alternatives, I do not know if they are faster.

Alternative 1

y <- rasterize(pts, b, 1)
m <- mask(b, y)

Alternative 2

v <- extract(b, pts)
r <- rasterize(pts, b, v)


来源:https://stackoverflow.com/questions/61547030/fastest-way-to-mask-raster-using-points

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!