R/remove_boundaries.R

Defines functions remove_boundaries

Documented in remove_boundaries

#' Mask boundary pixels from categorical raster
#'
#' @param x Categorical raster map
#' @param ncores Nu,ber of cores to use for parallel processing.
#' @param filename Optional. filename for writing raster to disk.
#' @return x with boundary pixels set to NA
#' @export

remove_boundaries <- function(x, ncores, filename = NULL) {

  layers <- raster::unstack(raster::layerize(x, falseNA = TRUE))

  cl <- parallel::makeCluster(ncores)
  doParallel::registerDoParallel(cl)
  masked <- foreach::foreach(i=layers, .packages=c("raster")) %dopar% {

    borders <- boundaries(i, classes = FALSE, asNA = TRUE)
    mask(i, borders, inverse = TRUE)

  }

  parallel::stopCluster(cl)

  stacked <- do.call(cover, masked)

  out <- mask(x, stacked)

  if(!is.null(filename)) {
    writeRaster(out, filename, overwrite = TRUE)
  }

  return(out)

}
juoe/spatialtools documentation built on May 25, 2019, 6:25 p.m.