Skip to content
Prev 23802 / 29559 Next

Needing to speed up a process involving calc() and cover() raster functions

Hi Benjamin,

Thanks for your answer

Sorry for not being precise. Actually, I want to threshold each band given
thresholds. I give the 1 value to each pixel, in each band, that is below
the threshold value.

Then, I want to cover all these bands into one, in order to combine all the
layers.

I tried different functions. Here are the different performances, if you
want to have a look. Te second function below is the fastest one. If you
think you have better, do not hesitate.

## FIRST FUNCTION

  fun1 = function() {
    threshs = c(.1,.2,.1)
    tamis = raster(classified); tamis[] = 0
    out = stack(lapply(1:nlayers(classified), function(i)
cover(clamp(classified[[i]], upper = threshs[[i]], useValues = FALSE),
tamis)))
    r = calc(out, sum)
    r[r[]==0] = NA; r[which(!is.na(r[]))] = 1
  }

## SECOND

  fun2 = function() {
    threshs = c(.1,.2,.1)
    out = lapply(1:nlayers(classified), function(i) clamp(classified[[i]],
upper = threshs[[i]], useValues = FALSE))
    r = out[[1]]
    for(i in 2:length(out)) {
      r = cover(out[[i]], r)
    }
    r[which(!is.na(r[]))] = 1
  }

## THIRD

  fun3 = function() {
    threshs = c(.1,.2,.1)
    out=lapply(1:nlayers(classified), function(i) {
      out[[i]] = calc(classified[[i]], function(x) {x[x >= threshs[i]] = NA;
                                                    x[x < threshs[i]] = 1;
                                                    return(x)})
    })
    r = out[[1]]
    for(i in 2:length(out)) {
      r = cover(out[[i]], r)
    }
  }

  system.time(fun1())
  system.time(fun2())
  system.time(fun3())
user  system elapsed
  63.05    2.67   65.81
user  system elapsed
  43.14    0.88  * 44.52 *
user  system elapsed
  48.67    1.51   50.62


Best,

Mathieu



2015-12-22 14:09 GMT+01:00 Benjamin Leutner <
benjamin.leutner at uni-wuerzburg.de>: