从平均值创建新的光栅图像

时间:2015-02-16 19:28:15

标签: r average raster

我有很长的栅格列表,我需要取一定数量的平均值并创建一个新图像。例如,如果我有栅格r1 r2 r3 r4 r5 r6 r7 r8 我想取r1和r2的平均值来给我一个图像,让我们说new1。然后我想平均r3和r4给我new2的图像。我尝试在caTools中使用runmean,但我无法获得所需的输出。如果我有8个光栅图像,那么使用两个窗口应该给我留下四个光栅图像。我知道栅格通常属于GIS网站,但我需要有关代码的帮助,所以我希望它在这里没问题。

1 个答案:

答案 0 :(得分:3)

假设您在一个文件夹中拥有所有栅格:rasdir(此文件夹中没有其他内容,但是要循环的栅格),设置环境变量:

rasdir="myrasters/"
raspaths <- list.files(path=rasdir, full.names=T)

假设所有栅格具有相同的范围和分辨率,它们可以叠加:

rascube <- stack(raspaths)

创建执行某些功能的功能,例如跨频段意味着

rascube是要循环的图像堆栈,win窗口大小,outdir是输出目录

rasfun <- function(x=rascube, win=2, outdir=getwd()){

#Sanity check
if(!(length(raspaths)/win)%%1==0){stop("Number of rasters must be divisible by window size")}

#Create ```mat``` , an index that determines how rasters in ```rascube``` are aggregated: 
#indices in the same row refer to rasters to be averaged into the ith output.

mat <- matrix(data=1:length(raspaths), ncol=win, byrow=T)

#Loop over ```rascube```, calculating the moving average as controlled by ```mat```

for (i in 1:nrow(mat)){

#Compute ith moving mean, You can alter this to compute a moving "whatever you like"
#Note the usage of ```[[ ]]``` to subset raster bands: see ```raster``` docu.
#Also Note the usage of ```na.rm=T```, just in case your images have NA's you dont care about

res_i <- sum(x[[ mat[i,1]:mat[i,win] ]], na.rm=T)/win #

#Write output to file: note how output filename is derived from the respective input rasters
#makes it possible to trace the outputs back to their source rasters.

writeRaster(x=res_i, filename=paste(mat[i,1:win], collapse=""),
format="GTiff", overwrite=T)

}
}

#Run newly created function on your stack of inputs with whatever args:
rasfun(x=rascube, win=2, outdir="moving_mean_rasters/")

注意:栅格数量必须可以被窗口大小整除,例如尝试在窗口大小为2的7个栅格上运行移动窗口计算将通过完整性检查失败。当然,您可以根据您认为最适合您的用例的方式更改功能。干杯!