# NOT RUN {
library("raster")
# Pixel-based processing on one band:
apply_multiplier <- function(inraster,multiplier)
{
# Note that inraster is received by this function as a 3-d array (col,row,band)
multiplied_raster <- inraster * multiplier
return(multiplied_raster)
}
tahoe_lidar_highesthit <-
setMinMax(raster(system.file(
"external/tahoe_lidar_highesthit.tif", package="spatial.tools")))
# Note that you can use any parallel backend that can be registered with foreach.
# sfQuickInit() will spawn a PSOCK cluster using the parallel package.
# sfQuickInit(cpus=2)
tahoe_lidar_highesthit_multiplied <- rasterEngine(
inraster=tahoe_lidar_highesthit,
fun=apply_multiplier,
args=list(multiplier=3.28084))
# sfQuickStop()
# }
# NOT RUN {
# Pixel-based processing on more than one band:
ndvi <- function(GRNIR_image)
{
# The input array will have dim(GRNIR_image)[3] equal
# to 3, because the input image has three bands.
# Note: the following two lines return an array,
# so we don't need to manually set the dim(ndvi) at the
# end. If we didn't use drop=FALSE, we'd need to
# coerce the output into a 3-d array before returning it.
red_band <- GRNIR_image[,,2,drop=FALSE]
nir_band <- GRNIR_image[,,3,drop=FALSE]
ndvi <- (nir_band - red_band)/(nir_band + red_band)
# The following is not needed in this case:
# dim(ndvi) <- c(dim(GRNIR_image)[1],dim(GRNIR_image)[2],1)
return(ndvi)
}
tahoe_highrez <- setMinMax(
brick(system.file("external/tahoe_highrez.tif", package="spatial.tools")))
sfQuickInit(cpus=2)
tahoe_ndvi <- rasterEngine(GRNIR_image=tahoe_highrez,fun=ndvi)
sfQuickStop()
# Focal-based processing:
mean_smoother <- function(inraster)
{
smoothed <- apply(inraster,3,mean)
return(smoothed)
}
# Apply the function to a 3x3 window:
sfQuickInit(cpus=2)
tahoe_3x3_smoothed <- rasterEngine(inraster=tahoe_highrez,fun=mean_smoother,window_dims=c(3,3))
sfQuickStop()
# Example with 7 x 7 window in full parallel mode:
sfQuickInit()
tahoe_7x7_smoothed <- rasterEngine(inraster=tahoe_highrez,fun=mean_smoother,window_dims=c(7,7))
sfQuickStop()
# }
Run the code above in your browser using DataLab