更快的降低光栅R分辨率的功能

Leo*_*sar 8 aggregate r raster r-raster

我正在使用光栅包来降低大栅格的分辨率,使用像这样的函数聚合

require(raster)    
x <- matrix(rpois(1000000, 2),1000)

a <-raster(x)
plot(a)

agg.fun <- function(x,...) 
    if(sum(x)==0){
        return(NA)
    } else {
        which.max(table(x))
    }

a1<-aggregate(a,fact=10,fun=agg.fun)
plot(a1)
Run Code Online (Sandbox Code Playgroud)

我必须聚合的光栅图像大得多34000x34000所以我想知道是否有更快的方法来实现agg.fun函数.

jba*_*ums 5

您可以gdalUtils::gdalwarp为此使用。对我来说,fasterAgg.Fun对于具有1,000,000个像元的栅格而言,它的效率比@JosephWood的效率低,但对于约瑟夫的更大示例而言,它的速度要快得多。它要求栅格存在于磁盘上,因此如果栅格在内存中,则将写入时间写入以下内容。

在下面,我使用了对fasterAgg.Fun返回最频繁的的修改,而不是返回其在块中的索引。

library(raster)
x <- matrix(rpois(10^8, 2), 10000)
a <- raster(x)

fasterAgg.Fun <- function(x,...) {
    myRle.Alt <- function (x1) {
        n1 <- length(x1)
        y1 <- x1[-1L] != x1[-n1]
        i <- c(which(y1), n1)
        x1[i][which.max(diff(c(0L, i)))]
    }

    if (sum(x)==0) {
        return(NA)
    } else {
        myRle.Alt(sort(x, method="quick"))
    }
}
system.time(a2 <- aggregate(a, fact=10, fun=fasterAgg.Fun))

##   user  system elapsed 
##  67.42    8.82   76.38

library(gdalUtils)
writeRaster(a, f <- tempfile(fileext='.tif'), datatype='INT1U')
system.time(a3 <- gdalwarp(f, f2 <- tempfile(fileext='.tif'), r='mode', 
                           multi=TRUE, tr=res(a)*10, output_Raster=TRUE))

##   user  system elapsed 
##   0.00    0.00    2.93
Run Code Online (Sandbox Code Playgroud)

请注意,有联系时,模式的定义略有不同:gdalwarp选择最高的值,而传递给aggregate上面的函数(通过which.max行为)选择最低的值(例如参见which.max(table(c(1, 1, 2, 2, 3, 4))))。

同样,将栅格数据存储为整数也很重要(适用时)。例如,如果数据存储为float(writeRaster默认值),则gdalwarp在我的系统上上述操作大约需要14秒。请参阅?dataType以获取可用的类型。

  • 对于计算机上未安装 GDAL 的 R 用户,“gdalUtilities::gdalwarp()”(来自我的 [**gdalUtilities**](https://github.com/JoshOBrien/gdalUtilities) 包)是另一种选择。它执行与上面的“gdalUtils::gdalwarp()”调用相同的计算,速度更快,并且不需要外部安装 GDAL。一个小的区别是它不接受 `output_Raster=` 参数。 (2认同)