R/texture.R

Defines functions texture

Documented in texture

#' Calculate texture measures using grass:r.neighbors and grass:r.texture through RQGIS.
#'
#' @param x Raster object or path to raster layer.
#' @param window_size pixel size of window, must be uneven
#' @param methods Which metrics to compute.
#' Options are: "average", "median", "mode", "minimum", "maximum", "stddev", "sum", "variance", "diversity", "interspersion",
#' "asm", "contrast", "corr", "var", "idm", "sa", "sv", "se", "entr", "dv", "de", "moc1", "moc2"
#' @param filename Optional filename for writing to disk.
#' @return Texture raster with all combinations of window sizes and methods.
#' @export

texture <- function(x, window_sizes = 3, methods = "average", filename = NULL) {

  if(nlayers(x) > 1){
    x <- unstack(x)
  } else {
    x <- list(x)
  }

  neighbors_methods <- c("average", "median", "mode", "minimum", "maximum", "stddev", "sum", "variance", "diversity", "interspersion")
  texture_methods <- c("asm", "contrast", "corr", "var", "idm", "sa", "sv", "se", "entr", "dv", "de", "moc1", "moc2")

  out_list <- lapply(x, function(layer){
    combinations <- purrr::cross2(methods, window_sizes)
    r_list <- purrr::map(combinations, function(combination){


      if(combination[[1]] %in% neighbors_methods) {

        tmpfile <- tempfile(fileext='.tif')

        r <- RQGIS::run_qgis(alg = "grass7:r.neighbors",
                             input = layer,
                             output = tmpfile,
                             size = combination[[2]],
                             method = combination[[1]],
                             load_output = TRUE)

      } else if (combination[[1]] %in% texture_methods) {

        inputname <- names(layer)
        # maybe find faster alternative
        layer <- raster::stretch(layer, datatype = "INT1U")

        tmpdir <- paste0(tempdir(), "\\", inputname, paste(unlist(combination), collapse = ""))

        unlink(tmpdir, recursive = TRUE)
        dir.create(tmpdir, showWarnings = FALSE)

        RQGIS::run_qgis(alg = "grass7:r.texture",
                        input = layer,
                        output = tmpdir,
                        size = combination[[2]],
                        method = combination[[1]])

        r <- raster(list.files(tmpdir, ".tif$", full.names = TRUE))

      }

      return(r)

    })

    s <- do.call(stack, r_list)
    bandnames <- purrr::map_chr(combinations, function(combination) {
      paste(names(layer) , paste(unlist(combination), collapse = "_"), sep = "_")
    })
    names(s) <- bandnames
    return(s)
  })

  out <- do.call(stack, out_list)

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

  return(out)

}
juoe/spatialtoolbox documentation built on May 7, 2019, 9:37 a.m.