请问是否有R语言中针对二维矩阵而非向量的滑动窗口方法?我需要对存储在矩阵中的图像应用中位数函数。
请问是否有R语言中针对二维矩阵而非向量的滑动窗口方法?我需要对存储在矩阵中的图像应用中位数函数。
在优秀的raster包中,函数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")
?focal
中的 Note: 部分所解释的那样)。相反,当前的 focal()
可以做到旧的 focal()
和 focalFilter()
所能做的一切。这是通过允许 w=
参数交替采用权重矩阵来实现的,这就是 focalFilter()
以前所做的。简而言之,现在只需要 filter()
就可以了,我会相应地修改帖子。感谢您指出这一点。 - Josh O'Brienma3x3.matrix()
比 focal()
稍慢一些,并且仅允许使用 3x3 的移动窗口。) - Josh O'Briensystem('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)
maj_filt_rast<- focal(input_rast, fun=modal, w=matrix(1,nrow=3,ncol=3))