You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中用循环实现多sigma参数高斯滤波并批量保存栅格?

批量高斯滤波处理栅格文件

问题描述

现有evi.tif栅格文件,需用sigma参数范围0.2到0.9、步长0.05的高斯滤波器批量模糊处理,输出文件命名格式为原始文件名+sigma值(如evi02.tif对应sigma=0.2,evi025.tif对应sigma=0.25)。已实现单参数处理,需要改为批量循环执行。

单参数处理代码:

evi = raster("path/evi.tif")

gf <- focalWeight(evi, 0.2, "Gauss")
r_gf <- focal(evi, w = gf)

writeRaster(r_gf, "path/evi02.tif")

输入栅格属性信息:

new("RasterLayer", file = new(".RasterFile", name = "C:\\Users\\nikos\\OneDrive\\Desktop\\tst\\evi.tif", 
    datanotation = "FLT8S", byteorder = "little", nodatavalue = -Inf, 
    NAchanged = FALSE, nbands = 1L, bandorder = "BIL", offset = 0L, 
    toptobottom = TRUE, blockrows = 256L, blockcols = 256L, driver = "gdal", 
    open = FALSE), data = new(".SingleLayerData", values = logical(0), 
    offset = 0, gain = 1, inmemory = FALSE, fromdisk = TRUE, 
    isfactor = FALSE, attributes = list(), haveminmax = FALSE, 
    min = Inf, max = -Inf, band = 1L, unit = "", names = "evi"), 
    legend = new(".RasterLegend", type = character(0), values = logical(0), 
        color = logical(0), names = logical(0), colortable = logical(0)), 
    title = character(0), extent = new("Extent", xmin = 983600, 
        xmax = 1033100, ymin = 976000, ymax = 1028800), rotated = FALSE, 
    rotation = new(".Rotation", geotrans = numeric(0), transfun = function () 
    NULL), ncols = 495L, nrows = 528L, crs = new("CRS", projargs = "+proj=lcc +lat_0=28.62510126 +lon_0=77 +lat_1=28.375 +lat_2=28.875 +x_0=1000000 +y_0=1000000 +datum=WGS84 +units=m +no_defs"), 
    history = list(), z = list())

批量处理解决方案

通过生成sigma参数序列,结合循环完成批量处理,关键是精准格式化输出文件名:

library(raster)

# 读取原始栅格(替换为你的文件路径)
evi <- raster("C:\\Users\\nikos\\OneDrive\\Desktop\\tst\\evi.tif")
# 生成sigma参数序列:0.2到0.9,步长0.05
sigma_list <- seq(from = 0.2, to = 0.9, by = 0.05)

# 循环处理每个sigma
for(sigma in sigma_list){
  # 创建高斯滤波权重矩阵
  gauss_weight <- focalWeight(evi, sigma, "Gauss")
  # 执行滤波操作
  filtered_raster <- focal(evi, w = gauss_weight)
  
  # 格式化文件名:移除sigma的小数点,匹配要求的命名规则
  sigma_label <- gsub("\\.", "", toString(round(sigma, 2)))
  output_file <- paste0("C:\\Users\\nikos\\OneDrive\\Desktop\\tst\\evi", sigma_label, ".tif")
  
  # 保存结果,允许覆盖已有文件
  writeRaster(filtered_raster, output_file, overwrite = TRUE)
}

代码关键点

  • seq(from = 0.2, to = 0.9, by = 0.05):自动生成所有需要的sigma参数,避免手动输入
  • round(sigma, 2):确保sigma值精度为两位小数,避免浮点数精度问题
  • gsub("\\.", "", ...):移除小数点,将0.2转为02、0.25转为025,匹配命名格式
  • overwrite = TRUE:若输出路径已有同名文件,直接覆盖(根据需求可调整)

内容的提问来源于stack exchange,提问作者Nikos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 07:45:31