Sliding window function in R
有人知道R中是否有针对2d矩阵的滑动窗口方法,而不仅仅是矢量。我需要对存储在matrix
中的图像应用中值函数
出色的光栅包中的功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | library(raster) ## Create some example data m <- matrix(1, ncol=10, nrow=10) diag(m) <- 2 r <- as(m,"RasterLayer") # Coerce matrix to RasterLayer object ## Apply a function that returns a single value when passed values of cells ## in a 3-by-3 window surrounding each focal cell rmean <- focal(r, w=matrix(1/9, ncol=3, nrow=3), fun=mean) rmedian <- focal(r, w=matrix(1/9, ncol=3, nrow=3), fun=median) ## Plot the results to confirm that this behaves as you'd expect par(mfcol=c(1,3)) plot(r) plot(rmean) plot(rmedian) ## Coerce results back to a matrix, if you so desire mmean <- as(rmean,"matrix") |
我知道这是一个老问题,但是在寻求解决类似问题时,我遇到过很多次。尽管栅格数据包中的焦点功能非常简单明了,但我发现使用大型栅格时它的速度非常慢。有很多方法可以尝试解决此问题,但是我发现的一种方法是使用系统命令来"白盒工具",这是一个由命令行驱动的栅格分析工具集。它的主要优点是可以并行执行工具,并且真正利用了多核CPU。我知道R有许多群集函数和程序包(用于随机森林模型栅格预测),但是我在R中的许多并行计算实现方面都感到吃力。Whitebox工具具有均值,最大值,多数,中位数等离散功能。 ..过滤器(更不用说对以DEM为中心的分析非常有用的地形处理工具的负载)。
一些示例代码,说明如何使用白盒工具在大型分类的土地覆盖栅格(nrow = 3793,ncol = 6789,ncell = 25750677)的R in中实现模态或多数过滤器(3x3窗口):
1 2 3 4 | system('C:/WBT2/target/release/whitebox_tools --wd="D:/Temp" ^ --run=MajorityFilter -v --input="input_rast.tif" ^ --output="maj_filt_rast.tif" --filterx=3 --filtery=3', wait = T, timeout=0, show.output.on.console = T) |
上面的代码用了不到3.5秒的时间来执行,同时,同样来自光栅包的使用"模态"的等效光栅包"聚焦"功能花了5分钟完成了以下代码:
1 | maj_filt_rast<- focal(input_rast, fun=modal, w=matrix(1,nrow=3,ncol=3)) |
获得编译和安装白盒工具有点麻烦,但是提供了很好的说明。在我看来,这是值得进行的工作,因为它使R中原本过慢的栅格过程运行得异常快,并且它使我可以使用系统命令保留R中所有内容的编码。