R/dual_thresholding.R

Defines functions dual_thresholding

Documented in dual_thresholding

#' @name dual_thresholding
#' @aliases dual_thresholding
#' @title Classify  a single-channel fisheye image using a dual thresholding, and return a binary fisheye image of canopy (0) and gap (1) pixels
#' @param img SpatRaster. A single layer  image imported by  the [terra::rast()] functionality.
#' @seealso Macfarlane 2011 \doi{10.1016/j.agrformet.2011.01.019}
#'
#' @returns A binary single-layer image (SpatRaster)
#' @importFrom terra rast nlyr ext values classify merge plot metags
#' @importFrom graphics hist
#'
#' @description
#' Dual thresholding method proposed by Macfarlane 2011 \doi{10.1016/j.agrformet.2011.01.019}
#'
#' @export

dual_thresholding <- function(img) {

  if (terra::nlyr(img) > 1) {
    stop("img must be a single-layer raster")
  }

  bins=255

  vals <- terra::values(img)
  vals <- vals[!is.na(vals)]

  if (length(vals) == 0) {
    stop("Image contains only NA values")
  }

  vmin <- min(vals)
  vmax <- max(vals)

  if (vmin == vmax) {
    stop("Image has no dynamic range")
  }

  h <- hist(
    vals,
    breaks = seq(vmin, vmax, length.out = 255),
    plot = FALSE
  )

  counts <- h$counts
  breaks <- h$breaks
  N <- length(counts)

  ## ------------------------------------------------------
  ## Locate dark peak (Lx)
  ## ------------------------------------------------------

  lo_end <- round(N * 55 / 256)

  x_hi <- lo_end
  diff <- 0

  while (diff < round(N * 10 / 256)) {

    rng <- seq_len(x_hi)

    Lx <- rng[which.max(counts[rng])]

    diff <- x_hi - Lx

    x_hi <- x_hi + round(N * 25 / 256)

    if (x_hi >= N) {
      break
    }
  }

  ## ------------------------------------------------------
  ## Locate bright peak (Hx)
  ## ------------------------------------------------------

  x_lo <- round(N * 150 / 256)
  diff <- 0

  while (diff < round(N * 10 / 256)) {

    rng <- seq(x_lo, N)

    Hx <- rng[which.max(counts[rng])]

    diff <- Hx - x_lo

    x_lo <- x_lo - round(N * 25 / 256)

    if (x_lo < 1) {
      break
    }
  }

  ## fallback

  if (Lx >= Hx) {

    Lx <- which.max(counts[1:floor(N / 3)])

    Hx <- which.max(counts[ceiling(2 * N / 3):N]) +
      ceiling(2 * N / 3) - 1
  }

  ## ------------------------------------------------------
  ## Upper corner
  ## ------------------------------------------------------

  Hi <- min(counts[Hx], length(vals) / bins)

  slope <- Hi / Hx

  alpha <- atan(1 / slope)

  O <- rep(-Inf, N)

  for (i in Lx:Hx) {

    H <- slope * i - counts[i]

    O[i] <- H * sin(alpha)
  }

  Upp <- which.max(O)

  ## ------------------------------------------------------
  ## Lower corner
  ## ------------------------------------------------------

  Lo <- min(counts[Lx], length(vals) / bins)

  slope <- Lo / (N - Lx)

  alpha <- atan(1 / slope)

  O <- rep(-Inf, N)

  for (i in Lx:Hx) {

    H <- slope * (N - i) - counts[i]

    O[i] <- H * sin(alpha)
  }

  Low <- which.max(O)

  ## ------------------------------------------------------
  ## Convert bin positions to image values
  ## ------------------------------------------------------

  Low_val <- breaks[Low]

  Upp_val <- breaks[Upp]

  ## ------------------------------------------------------
  ## Thresholds
  ## ------------------------------------------------------

  T_lo <- round(Low_val + (Upp_val - Low_val) / 4)

  T_mid <- round(Low_val + (Upp_val - Low_val) / 2)

  T_hi <- round(Low_val + (Upp_val - Low_val) * 3 / 4)

  ## ------------------------------------------------------
  ## Preliminary sky mask
  ## ------------------------------------------------------

  Sky <- img > Low_val

  patches <- terra::patches(
    Sky,
    directions = 4
  )

  fr <- terra::freq(patches)

  limit <- terra::ncell(img) # at the moment not worked

  small <- fr$value[
    fr$count < limit
  ]

  if (length(small) > 0) {

    ids <- terra::values(patches)

    sky_vals <- terra::values(Sky)

    sky_vals[ids %in% small] <- 0

    Sky[] <- sky_vals
  }

  Veg <- !Sky

  ## ------------------------------------------------------
  ## Dual threshold
  ## ------------------------------------------------------

  bw <- (img > T_hi & Sky) |
    (img > T_lo & Veg)

  bw <- terra::as.int(bw)

  names(bw) <- names(img)

  list(
    image = bw,
    thresholds = c(T_lo, T_hi),
    midpoint = T_mid,
    corners = round(c(Low_val, Upp_val)),
    bins = c(Low = Low, Upp = Upp),
    peaks = c(Lx = Lx, Hx = Hx)
  )
}

Try the coveR2 package in your browser

Any scripts or data that you put into this service are public.

coveR2 documentation built on Dec. 2, 2026, 5:07 p.m.