Replace specific value in each band of raster brick in R

白昼怎懂夜的黑 提交于 2019-12-24 08:46:41

问题


I have a multi-band (20 layers) raster loaded into R as a RasterBrick using brick(). My plan is to normalize each band from 0 to 1 using the approach that was proposed in this thread: https://stats.stackexchange.com/questions/70801/how-to-normalize-data-to-0-1-range

Here some sample code to visualize my problem:

for(j in 1:nlayers(tif)){
  min <- cellStats(tif[[j]],'min')
  max <- cellStats(tif[[j]],'max')
  for(i in 1:ncell(tif)){
    tif[i][j] <- (tif[i][j]-min)/(max-min)    
  }
}

"tif" contains the raster brick. "j" is the current layer of "tif", while "i" is the current cell of layer[[i]]. I think the rest is pretty straight forward. The problem now is that it takes hours without finishing to replace a single value in a specific band. Why is it taking so long without finishing?

Cheers, Kai


回答1:


Your approach is very inefficient because you are looping over each cell individually once at a time. This takes forever for larger rasters.

You can either use the approach from Geo-sp's answer (which I also wouldn't recommend if your raster is larger) or use the clusterR function:

norm <- function(x){(x-min)/(max-min)}

for(j in 1:nlayers(tif)){

  cat(paste("Currently processing layer:", j,"/",nlayers(tif), "\n"))

  min <- cellStats(tif[[j]],'min')
  max <- cellStats(tif[[j]],'max')

  #initialize cluster
  #number of cores to use for clusterR function (max recommended: ncores - 1)
  beginCluster(3)

  #normalize
  tif[[j]] <- clusterR(tif[[j]], calc, args=list(fun=norm), export=c('min',"max"))

  #end cluster
  endCluster()
}



回答2:


You can read all the layers using the stack function then normalizing them using:

s <- stack("Some Raster Layers")
snorm <- (s - minValue(s)) / (maxValue(s)- minValue(s))


来源:https://stackoverflow.com/questions/44266752/replace-specific-value-in-each-band-of-raster-brick-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!