Say I have a bunch of image slices as a 3D array:
myImages = array(runif(1024*1024*100), dim = c(1024,1024,100))
and want the pixel-wise median value.
medianImage = apply(myImages, c(1,2), median)
This process takes quite some time. Is there a faster alternative in R?
1
Rfast::rowMedians
is much faster, but it requires reshaping myImages
:
myImages <- array(runif(1024*1024*100), dim = c(1024,1024,100))
system.time(medianImage <- apply(myImages, c(1,2), median))
#> user system elapsed
#> 38.93 1.03 40.01
system.time({
dm <- dim(myImages)
dim(myImages) <- c(prod(dm[1:2]), dm[3])
medianImage2 <- `dim<-`(Rfast::rowMedians(myImages), dm[1:2])
dim(myImages) <- dm
})
#> user system elapsed
#> 1.58 0.29 1.86
all.equal(medianImage, medianImage2)
#> [1] TRUE
Compare to matrixStats::rowMedians
.
dim(myImages) <- c(prod(dm[1:2]), dm[3])
bench::mark(
Rfast = Rfast::rowMedians(myImages),
matrixStats = matrixStats::rowMedians(myImages),
min_iterations = 10
)
#> # A tibble: 2 × 6
#> expression min median `itr/sec` mem_alloc `gc/sec`
#> <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl>
#> 1 Rfast 1.23s 1.23s 0.806 8MB 0
#> 2 matrixStats 1.63s 1.64s 0.610 8.17MB 0
4