有人知道 R 中是否有用于 2d 矩阵而不仅仅是向量的滑动窗口方法。我需要将中值函数应用于存储在矩阵中的图像
2 回答
focal()
优秀的光栅包中的功能对此很有好处。它需要几个参数超出以下示例中所示的参数,如果需要,可用于指定非矩形滑动窗口。
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 工具具有用于均值、最大值、多数、中值等的离散函数。 ..
我如何使用白盒工具在大型分类土地覆盖栅格(nrow=3793,ncol=6789,ncell=25750677)的 R in 中实现模态或多数滤波器(3x3 窗口)的一些示例代码:
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 秒,同时使用同样来自 raster 包的“modal”等效的 raster 包“focal”功能,耗时 5 分钟完成,代码如下:
maj_filt_rast<- focal(input_rast, fun=modal, w=matrix(1,nrow=3,ncol=3))
编译和安装白盒工具有点烦人,但提供了很好的说明。在我看来,这是非常值得的,因为它使以前在 R 中非常慢的光栅进程运行得非常快,并且它允许我使用系统命令对 R 中的所有内容进行编码。