1

I am trying to use the ForestTools::mcws() function and segment_trees in R to segment a LiDAR point cloud using a CHM raster. However, when I try to run the function with the segment_trees() function from the lidR package, I get the following error :

Error: Invalid function provided as algorithm.

Here is the code I am using:

library(lidR)
library(ForestTools)
library(raster)
library(sf)

LASfile <- system.file("extdata", "Megaplot.laz", package="lidR")
las = readLAS(LASfile)
chm <- rasterize_canopy(las, 1, p2r(0.15), pkg = "raster")
vwf_fun <- function(x){x * 0.06 + 0.5}
WindowFilter <- vwf(CHM = chm, winFun = vwf_fun)
las <- segment_trees(las, ForestTools::mcws(WindowFilter, chm, minHeight = 2, format = "raster"))

I have checked the arguments I am passing to mcws(), and they seem to be correct. What could be causing this error, and how can I fix it?

JRR
  • 3,024
  • 2
  • 13
  • 37
Purple_Ad
  • 65
  • 6

1 Answers1

0

ForestTools::mcws is a function from the package ForestTools and is not designed to be compatible with lidR. lidR cannot accept any function as input and the developers must respect some convention to make their function compatible with lidR.

The function return a raster and thus can be made compatible with lidR. You can make the function compatible yourself

mcwatershed <- function(ttops, chm, minHeight) {
  f <- function(las) {
    res <- ForestTools::mcws(ttops, chm, minHeight, format = "raster")
    return(res)
  }
  
  f <- plugin_its(f)
  return(f)
}

Then

LASfile <- system.file("extdata", "Megaplot.laz", package="lidR")
las = readLAS(LASfile)
chm <- rasterize_canopy(las, 1, p2r(0.15), pkg = "raster")
vwf_fun <- function(x){x * 0.06 + 0.5}
WindowFilter <- vwf(CHM = chm, winFun = vwf_fun)
algo = mcwatershed(WindowFilter, chm, 2)
las <- segment_trees(las, algo)
plot(las, color = "treeID")
JRR
  • 3,024
  • 2
  • 13
  • 37