lidR Terra and Raster – How to Crop a Raster within a Function Using catalog_apply() in lidR with Terra Instead of Raster

lidrterra

I have older code to crop a chunk within a function (to avoid edge effects when later merging CHM tiles together (i.e., edge pixels derived without enough data. The extend of 1 is to avoid little gaps)), similar to the idea in example 1 here:
https://www.rdocumentation.org/packages/lidR/versions/2.2.1/topics/catalog_apply

Raster works but I would like to use Terra instead. I get this error:

Error: Cannot get an Extent object from argument y

I could try to convert the SpatExtent to an Extent, but it would be clunky. Maybe there's an easy way?

Below is part of my code (the Raster lines which work are commented out):

library(raster)
library(terra)

chunk <- ??? 
chm <- ??? 

bbox <- terra::ext(chunk)
bbox <- terra::extend(bbox, 1)
chm  <- terra::crop(chm, bbox)

#bbox <- raster::extent(chunk)
#bbox <- raster::extend(bbox, 1)
#chm  <- raster::crop(chm, bbox)

edits: minimal example, but with lidR code…

library(terra)
library(lidR)

ctgNorm <- readLAScatalog(system.file("extdata", "MixedConifer.laz", package="lidR"))

ctgNorm@output_options$drivers$Raster$param$overwrite <- TRUE

makeCHM_function = function(chunk) {
  las = readLAS(chunk)
  if (is.empty(las))
    return(NULL)
  chm <- grid_canopy(las, 1, pitfree(thresholds = c(0,2,5,10,15), max_edge = c(4, 2.5), subcircle = 0.3))
  rast(chm)
  # Wrong way to get extent... bbox <- terra::ext(chunk)
  # correct way:
  bbox <- lidR::extent(chunk)
  bbox <- terra::extend(bbox, 1)
  chm  <- terra::crop(chm, bbox)
  return(chm)
}

opt_chunk_size(ctgNorm) <- 25
opt_progress(ctgNorm) <- TRUE
opt_output_files(ctgNorm) <- "D:/processingTest20230509a/chm/chmNorm_tile_{XLEFT}_{YBOTTOM}"
myCHM <- catalog_apply(ctgNorm, makeCHM_function)

Best Answer

Your code can simply be written

library(terra)
library(lidR)

ctgNorm <- readLAScatalog(system.file("extdata", "MixedConifer.laz", package="lidR"))

ctgNorm@output_options$drivers$Raster$param$overwrite <- TRUE
opt_chunk_size(ctgNorm) <- 25
opt_progress(ctgNorm) <- TRUE
opt_output_files(ctgNorm) <- "D:/processingTest20230509a/chm/chmNorm_tile_{XLEFT}_{YBOTTOM}"
chm = rasterize_canopy(ctgNorm, 1, pitfree(thresholds = c(0,2,5,10,15), max_edge = c(4, 2.5), subcircle = 0.3))
Related Question