### LAScatalog Driver Configuration Examples Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates the structure and examples of drivers used by lidR's LAScatalog to manage output file writing. Drivers specify the function to use for writing, the file extension, and parameters for the write function. ```R list( write = raster::writeRaster, extension = ".tif", object = "x", path = "filename", param = list(format = "GTiff")) ``` ```R list( write = lidR::writeLAS, extension = ".las", object = "las", path = "file", param = list()) ``` -------------------------------- ### Example: Manual Tree Detection Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Provides examples for using the manual tree detection function. It shows a full manual detection process and how to use manual correction on automatically detected tree tops. ```R ## Not run: LASfile <- system.file("extdata", "MixedConifer.laz", package="lidR") las = readLAS(LASfile) # Full manual tree detection ttops = locate_trees(las, manual()) # Automatic detection with manual correction ttops = locate_trees(las, lmf(5)) ttops = locate_trees(las, manual(ttops)) ## End(Not run) ``` -------------------------------- ### Example: Locate Trees with lmf (Point Cloud) Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates using the locate_trees function with the lmf algorithm on a point cloud. It shows examples of fixed window size, variable window size based on height, and variable window size with custom arguments. ```R LASfile <- system.file("extdata", "MixedConifer.laz", package="lidR") las <- readLAS(LASfile, select = "xyzi", filter = "-inside 481250 3812980 481300 3813050") # 5x5 m fixed window size ttops <- locate_trees(las, lmf(5)) # variable windows size f <- function(x) { x * 0.07 + 3} ttops <- locate_trees(las, lmf(f)) # Very custom variable windows size f <- function(x, y, z) { x * 0.07 + y * 0.01 + z} ws_args <- list(x = "Z", y = "Intensity", z = 3) ttops <- locate_trees(las, lmf(f, ws_args = ws_args)) ``` -------------------------------- ### Read and Plot LAScatalog Example Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates reading a LAScatalog with a filter and plotting the catalog and its boundaries. This example showcases basic LAScatalog operations. ```R LASfile <- system.file("extdata", "Megaplot.laz", package="lidR") ctg <- readLAScatalog(LASfile, filter = "-drop_z_below 0.5") ctg2 <- catalog_boundaries(ctg, concavity = 1, length_threshold = 15) plot(ctg) plot(ctg2, add = TRUE) ``` -------------------------------- ### Example: Locate Trees with lmf (Raster) Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Illustrates using the locate_trees function with the lmf algorithm on a Canopy Height Model (CHM) raster. It includes examples for both fixed and variable window sizes. ```R chm <- rasterize_canopy(las, res = 1, p2r(0.15), pkg = "terra") ttops <- locate_trees(chm, lmf(5)) # variable window size f <- function(x) { x * 0.07 + 3 } ttops <- locate_trees(chm, lmf(f)) ``` -------------------------------- ### Example: Classify Ground using csf algorithm Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates how to read a LAS file, apply the csf() algorithm for ground classification, and then use classify_ground to assign ground points. ```R if (require(RCSF, quietly = TRUE)) { LASfile <- system.file("extdata", "Topography.laz", package="lidR") las <- readLAS(LASfile, select = "xyzrn", filter = "-inside 273450 5274350 273550 5274450") # (Parameters chosen mainly for speed) mycsf <- csf(TRUE, 1, 1, time_step = 1) las <- classify_ground(las, mycsf) #plot(las, color = "Classification") } ``` -------------------------------- ### Example: Segmenting Trees with silva2016 Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates reading a LAS file, creating a CHM, locating treetops, and then segmenting trees using the silva2016 algorithm. ```R LASfile <- system.file("extdata", "MixedConifer.laz", package="lidR") poi <- "-drop_z_below 0 -inside 481280 3812940 481320 3812980" las <- readLAS(LASfile, select = "xyz", filter = poi) col <- pastel.colors(200) chm <- rasterize_canopy(las, res = 0.5, p2r(0.3)) ker <- matrix(1,3,3) chm <- terra::focal(chm, w = ker, fun = mean, na.rm = TRUE) ttops <- locate_trees(chm, lmf(4, 2)) las <- segment_trees(las, silva2016(chm, ttops)) #plot(las, color = "treeID", colorPalette = col) ``` -------------------------------- ### Example: Segmenting Trees with li2012 Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates reading a LAS file, filtering points, and segmenting trees using the li2012 algorithm with custom parameters. ```R LASfile <- system.file("extdata", "MixedConifer.laz", package="lidR") poi <- "-drop_z_below 0 -inside 481280 3812940 481320 3812980" las <- readLAS(LASfile, select = "xyz", filter = poi) col <- pastel.colors(200) las <- segment_trees(las, li2012(dt1 = 1.4)) #plot(las, color = "treeID", colorPalette = col) ``` -------------------------------- ### Example: Standalone silva2016 Usage Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Shows how to use the silva2016 algorithm as a standalone function, processing a CHM and treetops to segment crowns. ```R chm <- raster("chm.tif") # Assuming ttops are already computed and loaded # ttops <- locate_trees(chm, lmf(3)) crowns <- silva2016(chm, ttops)() # The () calls the function with default parameters ``` -------------------------------- ### Install lidR Dependencies on GNU/Linux Source: https://cran.r-project.org/web/packages/lidR/readme/README Provides commands for installing necessary dependencies for the lidR package on Ubuntu and Fedora Linux distributions. This includes adding PPAs and using package managers like apt-get and dnf. ```Shell # Ubuntu sudo add-apt-repository ppa:ubuntugis/ubuntugis-unstable sudo apt-get update sudo apt-get install libgdal-dev libgeos++-dev libudunits2-dev libproj-dev libx11-dev libgl1-mesa-dev libglu1-mesa-dev libfreetype6-dev libxt-dev libfftw3-dev # Fedora sudo dnf install gdal-devel geos-devel udunits2-devel proj-devel mesa-libGL-devel mesa-libGLU-devel freetype-devel libjpeg-turbo-devel ``` -------------------------------- ### Example: Reading a LAS file with specific attributes and filter Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates how to read a LAS file, selecting only 'xyz' coordinates and applying a filter to keep the first return of each point. ```R LASfile <- system.file("extdata", "Megaplot.laz", package="lidR") las = readLAS(LASfile, select = "xyz") las = readLAS(LASfile, select = "xyzi", filter = "-keep_first") ``` -------------------------------- ### Example: Classify Noise using ivf algorithm Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Shows how to read a LAS file, artificially add outliers, and then use classify_noise with the ivf() algorithm to identify and classify noise points. ```R LASfile <- system.file("extdata", "Topography.laz", package="lidR") las <- readLAS(LASfile, filter = "-inside 273450 5274350 273550 5274450") # Add 20 artificial outliers set.seed(314) id = round(runif(20, 0, npoints(las))) set.seed(42) err = runif(20, -50, 50) las$Z[id] = las$Z[id] + err # Using IVF las <- classify_noise(las, ivf(5,2)) #plot(las, color = "Classification") # Remove outliers using filter_poi() las_denoise <- filter_poi(las, Classification != LASNOISE) ``` -------------------------------- ### Example Usage of High-Level Function (R) Source: https://cran.r-project.org/web/packages/lidR/vignettes/lidR-LAScatalog-engine Provides examples of how to use a high-level function like 'find_deadtrees' with different inputs. It shows usage with a single LAS object and with a LAScatalog, demonstrating parallel processing capabilities using the 'future' package. ```R # This will works las <- readLAS(...) deads <- find_deadtrees(las, 0.5, 3) # And this too library(future) ctg <- readLAScatalog(...) opt_chunk_size(ctg) <- 800 opt_chunk_buffer(ctg) <- 30 plan(multissesion, workers = 4L) deads <- find_deadtrees(ctg, 0.5, 3) ``` -------------------------------- ### LAS Catalog Processing Examples Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates reading a LAS catalog, plotting it with chunk patterns, and modifying chunk processing options like size, buffer, and alignment. It also shows how to set output file templates and summarize the catalog. ```R LASfile <- system.file("extdata", "Megaplot.laz", package="lidR") ctg = readLAScatalog(LASfile) plot(ctg, chunk_pattern = TRUE) opt_chunk_size(ctg) <- 150 plot(ctg, chunk_pattern = TRUE) opt_chunk_buffer(ctg) <- 10 plot(ctg, chunk_pattern = TRUE) opt_chunk_alignment(ctg) <- c(270,250) plot(ctg, chunk_pattern = TRUE) summary(ctg) opt_output_files(ctg) <- "/path/to/folder/templated_filename_{XBOTTOM}_{ID}" summary(ctg) ``` -------------------------------- ### Basic LAS File Reading Example Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates reading a LAS file with specific attributes selected, excluding intensity and angle. ```R LASfile <- system.file("extdata", "Megaplot.laz", package="lidR") las = readLAS(LASfile, select = "* -i -a") ``` -------------------------------- ### lidR Clipping Examples Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates how to clip lidar data using different geometric shapes and input types (LAS object vs. LAScatalog) with functions like clip_rectangle, clip_roi, and clip_transect. ```R LASfile <- system.file("extdata", "Megaplot.laz", package="lidR") # Load the file and clip the region of interest las = readLAS(LASfile, select = "xyz", filter = "-keep_first") subset1 = clip_rectangle(las, 684850, 5017850, 684900, 5017900) # Do not load the file(s), extract only the region of interest # from a bigger dataset ctg = readLAScatalog(LASfile, progress = FALSE, filter = "-keep_first") subset2 = clip_rectangle(ctg, 684850, 5017850, 684900, 5017900) # Extract all the polygons from a shapefile f <- system.file("extdata", "lake_polygons_UTM17.shp", package = "lidR") lakes <- sf::st_read(f, quiet = TRUE) subset3 <- clip_roi(las, lakes) # Extract the polygons for a catalog, write them in files named # after the lake names, do not load anything in R opt_output_files(ctg) <- paste0(tempfile(), "_{LAKENAME_1}") new_ctg = clip_roi(ctg, lakes) plot(new_ctg) # Extract a transect p1 <- c(684800, y = 5017800) p2 <- c(684900, y = 5017900) tr1 <- clip_transect(las, p1, p2, width = 4) ## Not run: plot(subset1) plot(subset2) plot(subset3) plot(tr1, axis = TRUE, clear_artifacts = FALSE) ## End(Not run) ``` -------------------------------- ### Example: Track Sensor with Roussel2020 Algorithm Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates how to use the track_sensor function with the Roussel2020 algorithm to compute sensor trajectories from a LAS file. It includes reading a LAS file, calling track_sensor, and plotting the results. ```R LASfile <- system.file("extdata", "Topography.laz", package="lidR") las = readLAS(LASfile) #plot(las) # pmin = 15 because it is an extremely small file # strongly decimated to reduce its size. There are # actually few multiple returns flightlines <- track_sensor(las, Roussel2020(pmin = 15)) plot(las@header) plot(sf::st_geometry(flightlines), add = TRUE) #plot(las) |> add_flightlines3d(flightlines, radius = 10) ## Not run: # With a LAScatalog "-drop_single" and "-thin_pulses_with_time" # are used by default ctg = readLAScatalog("folder/") flightlines <- track_sensor(ctg, Roussel2020(pmin = 15)) plot(flightlines) ## End(Not run) ``` -------------------------------- ### lidR R Package: Initial LiDAR Data Processing Example Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates reading a LAS file, extracting XYZ coordinates, fitting a circle to the point cloud, and plotting the results. It also shows how to fit a half-circle to a subset of the data. ```R LASfile <- system.file("extdata", "dbh.laz", package="lidR") las <- readTLS(LASfile, select = "xyz") xyz = sf::st_coordinates(las) circle = fit_circle(xyz) plot(xyz, asp = 1, pch = 19, cex = 0.1) symbols(circle$center_x, circle$center_y, circles = circle$radius, add = TRUE, fg = "red", inches = FALSE) trunk = las[circle$inliers] # Fitting a half-circle half = xyz[xyz[,1] > 101.45,] circle = fit_circle(half) plot(half, asp = 1, pch = 19, cex = 0.1) symbols(circle$center_x, circle$center_y, circles = circle$radius, add = TRUE, fg = "red", inches = FALSE) circle$covered_arc_degree ``` -------------------------------- ### Parallel Processing Setup Source: https://cran.r-project.org/web/packages/lidR/vignettes/lidR-LAScatalog-engine Illustrates how to configure parallel processing using the 'future' package in R. It shows how to register a parallelization strategy, such as running 4 chunks concurrently using `plan(multissesion, workers = 4L)`. ```R library(future) plan(multissesion, workers = 4L) ``` -------------------------------- ### Example: Rasterize Canopy with Pit-free Algorithm Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates how to use the `rasterize_canopy` function with the `pitfree` algorithm to create a canopy height model (CHM). It shows basic usage and how to adjust parameters like `max_edge`. ```R LASfile <- system.file("extdata", "MixedConifer.laz", package="lidR") poi = "-drop_z_below 0 -inside 481280 3812940 481330 3812990" las <- readLAS(LASfile, filter = poi) col <- height.colors(50) # Basic triangulation and rasterization of first returns chm <- rasterize_canopy(las, res = 0.5, dsmtin()) plot(chm, col = col) # Khosravipour et al. pitfree algorithm chm <- rasterize_canopy(las, res = 0.5, pitfree(c(0,2,5,10,15), c(0, 1.5))) plot(chm, col = col) ## Not run: # Potentially complex concave subset of point cloud x = c(481340, 481340, 481280, 481300, 481280, 481340) y = c(3812940, 3813000, 3813000, 3812960, 3812940, 3812940) las2 = clip_polygon(las,x,y) plot(las2) # Because the TIN interpolation is done within the convex hull of the point cloud # dummy pixels are interpolated that are correct according to the interpolation # method used, but meaningless in our CHM chm <- rasterize_canopy(las2, res = 0.5, pitfree(max_edge = c(0, 1.5))) plot(chm, col = col) chm = rasterize_canopy(las2, res = 0.5, pitfree(max_edge = c(3, 1.5))) plot(chm, col = col) ## End(Not run) ``` -------------------------------- ### Example: Classifying Ground Points with lidR Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates how to read a LAS file and apply the `classify_ground` function using the `mcc` algorithm. It highlights the usage of scale and curvature parameters, which are crucial for accurate ground segmentation. ```R if (require(RMCC, quietly = TRUE)) { LASfile <- system.file("extdata", "Topography.laz", package="lidR") las <- readLAS(LASfile, select = "xyzrn", filter = "-inside 273450 5274350 273550 5274450") las <- classify_ground(las, mcc(1.5,0.3)) #plot(las, color = "Classification") } ``` -------------------------------- ### R Nested Parallelism Example Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates defining a function for parallel processing and applying it using catalog_map with specific worker configurations. It illustrates how to set up parallel execution plans and thread counts for nested parallelism. ```R myfun = function(las, ws, ...) { las <- normalize_height(las, tin()) tops <- locate_tree(las, lmf(ws)) return(tops) } out <- catalog_map(ctg, myfun, ws = 5) ``` ```R plan(multisession, workers = 2L) set_lidr_threads(2L) catalog_map(ctg, myfun, ws = 5) ``` -------------------------------- ### Locate Tree Tops Example Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates reading a LAS file and locating tree tops using the lidR package. It shows how to select specific point attributes and filter points within a defined bounding box before applying the tree locating algorithm. ```R LASfile <- system.file("extdata", "MixedConifer.laz", package="lidR") las <- readLAS(LASfile, select = "xyz", filter = "-inside 481250 3812980 481300 3813030") ttops <- locate_trees(las, lmf(ws = 5)) ``` -------------------------------- ### Managing Sensor and Index Properties Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates setting and querying sensor types ('tls', 'als') and spatial index types ('quadtree', 'voxelpartition') for LAS and LAScatalog objects. This includes examples of how these settings affect processing. ```R sensor(las, h = TRUE) index(las, h = TRUE) sensor(las) <- "tls" sensor(las, h = TRUE) index(las, h = TRUE) index(las) <- "quadtree" sensor(las, h = TRUE) index(las, h = TRUE) las <- readTLSLAS(LASfile) sensor(las, h = TRUE) index(las, h = TRUE) index(las) <- "voxelpartition" index(las, h = TRUE) ctg = readTLSLAScatalog(LASfile) index(ctg) <- "voxelpartition" sensor(ctg, h = TRUE) index(ctg, h = TRUE) ``` -------------------------------- ### R Example: Adding and Removing LAS Attributes Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates how to add custom attributes using `add_attribute` and `add_lasattribute`, update headers, add RGB data, and remove attributes using `remove_lasattribute`. ```R LASfile <- system.file("extdata", "example.laz", package="rlas") las <- readLAS(LASfile, select = "xyz") print(las) print(header(las)) x <- 1:30 # Using add_attribute (header not updated, not written to file) las <- add_attribute(las, x, "mydata") print(las) print(header(las)) # Using add_lasattribute (header updated, written to file) las <- add_lasattribute(las, x, "mydata2", "A new data") print(las) print(header(las)) # Updating header for an existing attribute added with add_attribute las <- add_attribute(las, x, "newattr") # Add attribute first las <- add_lasattribute(las, name = "newattr", desc = "Amplitude") # Update header print(header(las)) # Remove an extra bytes attribute las <- remove_lasattribute(las, "mydata2") print(las) print(header(las)) las <- remove_lasattribute(las, "mydata") print(las) print(header(las)) ``` -------------------------------- ### Apply User-Defined Function to LAS Catalog (Simplified) Source: https://cran.r-project.org/web/packages/lidR/refman/lidR A simplified example demonstrating how to apply a user-defined function `my_tree_detection_method` to a LAS catalog using `catalog_map`. This showcases basic processing without explicit buffer handling in the function itself. ```R # 1. Build the user-defined function that analyzes a point cloud. my_tree_detection_method <- function(las, ws) { # Find the tree tops using a user-developed method # (here simply a LMF for the example). ttops <- locate_trees(las, lmf(ws)) return(ttops) } # 2. Build a project LASfile <- system.file("extdata", "MixedConifer.laz", package="lidR") ctg <- readLAScatalog(LASfile) plot(ctg) # 3. Set some processing options. # For this dummy example, the chunk size is 100 m and the buffer is 10 m opt_chunk_buffer(ctg) <- 10 opt_chunk_size(ctg) <- 100 # small because this is a dummy example. opt_chunk_alignment(ctg) <- c(-50, -35) # Align such as it creates 2 chunks only. opt_select(ctg) <- "xyz" # Read only the coordinates. opt_filter(ctg) <- "-keep_first" # Read only first returns. # 4. Apply a user-defined function to take advantage of the internal engine opt <- list(need_buffer = TRUE) # catalog_apply will throw an error if buffer = 0 output <- catalog_map(ctg, my_tree_detection_method, ws = 5, .options = opt) ``` -------------------------------- ### Example: Reading a LAS file with multiple attributes and complex filter Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Shows reading a LAS file, selecting 'xyz', intensity, and scan angle, and applying a filter to keep the first return and drop points with Z values below 0. ```R LASfile <- system.file("extdata", "Megaplot.laz", package="lidR") las = readLAS(LASfile, select = "xyziar", filter = "-keep_first -drop_z_below 0") ``` -------------------------------- ### Controlling Catalog Options: Buffer Requirement Source: https://cran.r-project.org/web/packages/lidR/vignettes/lidR-LAScatalog-engine Demonstrates how catalog options can enforce processing requirements, such as ensuring a buffer is present for operations like rasterize_terrain. This example shows an error when the buffer is set to 0. ```R opt_chunk_buffer(ctg) <- 0 rasterize_terrain(ctg, 1, tin()) #> Error: A buffer greater than 0 is required to process the catalog. ``` -------------------------------- ### Custom Driver for Appending sf to SQLite Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Provides an example of creating a custom driver to append sf objects to a SQLite database. This involves defining a specific write function that connects to the database, writes the table, and disconnects. The driver is then assigned to the 'sf' type in the LAScatalog's output options. ```R dbWrite_sf = function(x, path, name) { x <- sf::st_drop_geometry(x) con <- RSQLite::dbConnect(RSQLite::SQLite(), path) RSQLite::dbWriteTable(con, name, x, append = TRUE) RSQLite::dbDisconnect(con) } ctg@output_options$drivers$sf = list( write = dbWrite_sf, extension = ".sqlite", object = "x", path = "path", param = list(name = "layername")) opt_output_files(ctg) <- paste0(tempdir(), "/mysqlitefile") ``` -------------------------------- ### lidR S3/S4 Methods Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Documentation for S3 and S4 generic functions applied to lidR objects like LAS, LAScatalog, LASheader, lidRAlgorithm, and raster_template. These include methods for printing, summarizing, getting dimensions, and accessing names. ```APIDOC S3 Methods for lidR Objects: print(x, ...) - Description: Prints an object of class 'LAScatalog', 'lidRAlgorithm', or 'raster_template'. - Parameters: - x: The lidR object to print. - ...: Additional arguments. summary(object, ...) - Description: Provides a summary of an object of class 'LAS' or 'LAScatalog'. - Parameters: - object: The lidR object to summarize. - ...: Additional arguments. dim(x) - Description: Returns the dimensions of an object of class 'LAS' or 'LAScatalog'. - Parameters: - x: The lidR object. - Returns: A vector of integers representing the dimensions. ncol.LAS(x) - Description: Returns the number of columns (attributes) in a LAS object. - Parameters: - x: The LAS object. - Returns: An integer. nrow.LAScatalog(x) - Description: Returns the number of rows (points) in a LAScatalog object. - Parameters: - x: The LAScatalog object. - Returns: An integer. names(x) - Description: Returns the names of the attributes for a 'LAS' or 'LASheader' object. - Parameters: - x: The LAS or LASheader object. - Returns: A character vector of attribute names. rbind(...) - Description: Combines multiple LAS objects into a single LAS object. - Parameters: - ...: One or more LAS objects. - Returns: A combined LAS object. npoints(x, ...) - Description: Returns the number of points in a LAS object. - Parameters: - x: The LAS object. - ...: Additional arguments. - Returns: An integer. S4 Methods for lidR Objects: density(x, ...) - Description: Computes the density of points for 'LAS', 'LASheader', or 'LAScatalog' objects. - Parameters: - x: The lidR object (LAS, LASheader, or LAScatalog). - ...: Additional arguments. - Returns: A numeric value representing point density. ``` -------------------------------- ### lidR Data Processing Examples Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates basic LiDAR data processing tasks using the lidR package, including reading LAS files, reading spatial data (shapefiles), merging spatial attributes to LiDAR points, and filtering points based on spatial attributes. ```R LASfile <- system.file("extdata", "Megaplot.laz", package="lidR") shp <- system.file("extdata", "lake_polygons_UTM17.shp", package = "lidR") las <- readLAS(LASfile, filter = "-keep_random_fraction 0.1") lakes <- sf::st_read(shp, quiet = TRUE) # The attribute "inlake" does not exist in the shapefile. # Points are classified as TRUE if in a polygon las <- merge_spatial(las, lakes, "inlakes") # New attribute 'inlakes' is added. names(las) forest <- filter_poi(las, inlakes == FALSE) #plot(forest) # The attribute "LAKENAME_1" exists in the shapefile. # Points are classified with the values of the polygons las <- merge_spatial(las, lakes, "LAKENAME_1") # New column 'LAKENAME_1' is added. names(las) ``` -------------------------------- ### Gatziolis2019 Sensor Tracking Algorithm Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Documentation for the Gatziolis2019 sensor tracking algorithm, which reconstructs aircraft trajectories from multi-return LiDAR data. It details the algorithm's parameters, methodology based on closest point approach and cubic spline fitting (though spline fitting is not included), and provides usage examples. ```APIDOC Gatziolis2019(SEGLENFactor = 1.0059, AngleFactor = 0.8824, deltaT = 0.5) Description: Implements an algorithm from Gatziolis and McGaughey 2019 for sensor tracking using multiple returns. It computes the intersection in space of lines passing through the first and last returns. Arguments: SEGLENFactor: scalar. Weighting factor for the distance between 1st and last pulse returns. Defaults to 1.0059. AngleFactor: scalar. Weighting factor for the view angle of the mother pulse of a return. Defaults to 0.8824. deltaT: scalar. TimeBlock duration in seconds. Defaults to 0.5. Details: The algorithm involves a closest point approach (CPA) and cubic spline fitting. The spline fitting step is a post-processing step and is not included in this implementation. The source code is a modification of the original to fit the lidR package. References: Gatziolis, D., & McGaughey, R. J. (2019). Reconstructing Aircraft Trajectories from Multi-Return Airborne Laser-Scanning Data. Remote Sensing, 11(19), 2258. Example Usage: # A valid file properly populated LASfile <- system.file("extdata", "Topography.laz", package="lidR") las = readLAS(LASfile) flightlines <- track_sensor(las, Gatziolis2019()) plot(las@header) plot(flightlines, add = TRUE) ``` -------------------------------- ### R: `raster_alignment` Configuration Examples Source: https://cran.r-project.org/web/packages/lidR/refman/lidR This section details how to configure `raster_alignment` to ensure chunks are aligned with raster output, preventing edge artifacts. It shows examples of setting `raster_alignment` to a resolution value or a list containing resolution and starting point. ```R # check if chunks are aligned with a raster of resolution 20 raster_alignment = 20 raster_alignment = list(res = 20) # check if chunks are aligned with a raster of resolution 20 # that starts at (0,10) raster_alignment = list(res = 20, start = c(0,10)) ``` -------------------------------- ### Example usage: Process single LAS file Source: https://cran.r-project.org/web/packages/lidR/vignettes/lidR-catalog-apply-examples Demonstrates the basic usage of the `filter_noise` function on a single LAS file loaded into memory. It reads a LAS file, applies the custom noise filter, and writes the processed data to a new file. ```R las <- readLAS("file.las") las <- filter_noise(las, sensitivity = 1.2) writeLAS(las, "denoised-file.las") ``` -------------------------------- ### R: Nested Parallelism Example Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Shows an example of nested parallelism where both chunk-based and algorithm-based parallelism are active. The lidR package manages this by prioritizing chunk-based parallelism and disabling OpenMP for individual chunk computations to prevent oversubscription. ```R library(future) plan(multisession, workers = 4L) set_lidr_threads(4L) ctg <- readLAScatalog("folder/") out <- locate_trees(ctg, lmf(2)) ``` -------------------------------- ### Read LAS File and Get Bounding Box Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates reading a LAS file using the rlas package and retrieving its bounding box and extent. Requires the rlas package. ```R f <- system.file("extdata", "example.las", package="rlas") las <- readLAS(f) st_bbox(las) ext(las) ``` -------------------------------- ### Retrieving Chunk Bounding Box Source: https://cran.r-project.org/web/packages/lidR/vignettes/lidR-LAScatalog-engine Shows how to get the bounding box of a chunk, which represents the chunk's extent without the buffer. This is useful for unbuffering results before final merging. ```R print(chunk) # Example output: #> class : LAScluster #> features : 1 #> extent : 684800, 684950, 5017810, 5017960 (xmin, xmax, ymin, ymax) #> crs : +proj=utm +zone=17 +datum=NAD83 +units=m +no_defs raster::extent(chunk) # Example output: #> class : Extent #> xmin : 684800 #> xmax : 684950 #> ymin : 5017810 #> ymax : 5017960 sf::st_bbox(chunk) # Example output: #> xmin ymin xmax ymax #> 684800 5017810 684950 5017960 ``` -------------------------------- ### Process LiDAR Catalog with lidR Functions Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates building a LAS catalog, summarizing its processing plan, and applying lidR functions like pixel_metrics, tree_detection, rasterize_terrain, and normalize_height. It also shows how to configure chunk size and output file paths for memory-efficient processing. ```R ## Not run: # Build a catalog ctg <- readLAScatalog("filder/to/las/files/", filter = "-keep_first") # Summary gives a summary of how the catalog will be processed summary(ctg) # We can seamlessly use lidR functions hmean <- pixel_metrics(ctg, ~~mean(Z), 20) ttops <- tree_detection(ctg, lmf(5)) # For low memory config it is probably advisable not to load entire files # and process chunks instead opt_chunk_size(ctg) <- 500 # Sometimes the output is likely to be very large # e.g. large coverage and small resolution dtm <- rasterize_terrain(ctg, 1, tin()) # In that case it is advisable to write the output(s) to files opt_output_files(ctg) <- "path/to/folder/DTM_chunk_{XLEFT}_{YBOTTOM}" # Raster will be written to disk. The list of written files is returned # or, in this specific case, a virtual raster mosaic. dtm <- rasterize_terrain(ctg, 1, tin()) # When chunks are files the original names of the las files can be preserved opt_chunk_size(ctg) <- 0 opt_output_files(ctg) <- "path/to/folder/DTM_{ORIGINALFILENAME}" dtm <- rasterize_terrain(ctg, 1, tin()) # For some functions, files MUST be written to disk. Indeed, it is certain that R cannot # handle the entire output. opt_chunk_size(ctg) <- 0 opt_output_files(ctg) <- "path/to/folder/{ORIGINALFILENAME}_norm" opt_laz_compression(ctg) <- TRUE new_ctg <- normalize_height(ctg, tin()) # The user has access to the catalog engine through the functions catalog_apply # and catalog_map output <- catalog_apply(ctg, FUN, ...) ## End(Not run) ``` -------------------------------- ### Error when buffer is insufficient for lidR operation Source: https://cran.r-project.org/web/packages/lidR/vignettes/lidR-LAScatalog-engine Shows an example where a lidR function, rasterize_terrain, fails because the chunk buffer is set to 0. The error message indicates that a buffer greater than 0 is required for such operations. ```R opt_chunk_buffer(ctg) <- 0 rasterize_terrain(ctg, 1, tin()) #> Error: A buffer greater than 0 is required to process the catalog. ``` -------------------------------- ### lidR: `sp` to `sf` Object Transition Source: https://cran.r-project.org/web/packages/lidR/news/news Details function replacements in lidR for transitioning from `sp` package objects to `sf` package objects. New functions return `sf` or `sfc` objects. Old functions are retained for backward compatibility but are not documented for new users. ```APIDOC APIDOC: lidR Function Replacements (sp to sf) - tree_metrics() and delineate_crowns() are replaced by crown_metrics(). - crown_metrics() offers the same functionality and more. - Returns: sf or sfc objects. - find_trees() is replaced by locate_trees(). - Returns: sf or sfc objects. ``` -------------------------------- ### Enable On-the-Fly Loading of On-disk CHM Source: https://cran.r-project.org/web/packages/lidR/news/news Introduces the capability for `silva2016` to load (not too big) on-disk canopy height models (CHM) on the fly. This improves memory management for large datasets. ```R Fix: [#694](https://github.com/r-lidar/lidR/issues/694) `silva2016` can load (not too big) ondisk chm on the fly. ``` -------------------------------- ### Create LAS Object Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates how to create LAS objects from data frames or existing LAS objects. It covers coordinate quantization based on header scale factors and handling external headers. ```R # Read a las/laz file LASfile <- system.file("extdata", "example.laz", package="rlas") las <- readLAS(LASfile) las # Creation of a LAS object out of external data data <- data.frame(X = runif(100, 0, 100), Y = runif(100, 0, 100), Z = runif(100, 0, 20)) # 'data' has many decimal digits data # Create a default header and quantize *by reference* # the coordinates to fit with offset and scale factors cloud <- LAS(data) # 'data' has been updated and coordinates were quantized data cloud # Be careful when providing a header the function assumes that # it corresponds to the data and won't quantize the coordinates data <- data.frame(X = runif(100, 0, 100), Y = runif(100, 0, 100), Z = runif(100, 0, 20)) header <- header(las) # This works but triggers warnings and creates an invalid LAS object cloud <- LAS(data, header) las_check(cloud) ``` -------------------------------- ### Loading and Initializing LiDAR Data Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Loads a LAS file using readLAS and filters it to keep a random fraction of points. It also sets up color palettes and defines anonymous functions for metric calculation. ```R LASfile <- system.file("extdata", "Megaplot.laz", package="lidR") las <- readLAS(LASfile, filter = "-keep_random_fraction 0.5") col <- sf::sf.colors(15) fun1 <- ~list(maxz = max(Z)) fun2 <- ~list(q85 = quantile(Z, probs = 0.85)) ``` -------------------------------- ### Error Message Example Source: https://cran.r-project.org/web/packages/lidR/vignettes/lidR-LAScatalog-engine Illustrates a typical error message encountered during chunk processing. It indicates the chunk number where the error occurred and provides specific R code to load that chunk for detailed inspection and debugging. ```R #> An error occurred when processing the chunk 9. Try to load this chunk with: #> chunk <- readRDS("/tmp/RtmpTozKLu/chunk9.rds") #> las <- readLAS(chunk) #> No ground point found. ``` -------------------------------- ### Example 1 - Raster Output Source: https://cran.r-project.org/web/packages/lidR/vignettes/lidR-LAScatalog-class Loads a LAScatalog and processes each file sequentially to return a raster into R. This is suitable when the aggregated output can fit into memory. ```R ctg <- readLAScatalog("path/to/las/files/") hmean <- pixel_metrics(ctg, ~mean(Z), 20) ``` -------------------------------- ### Applying Catalog Options via catalog_apply() Source: https://cran.r-project.org/web/packages/lidR/vignettes/lidR-LAScatalog-engine Shows how to pass specific processing options, like 'need_buffer = TRUE', directly to catalog_apply. This allows fine-grained control over how chunks are processed and ensures compatibility with certain functions. ```R routine <- function(chunk){ las <- readLAS(chunk) if (is.empty(las)) return(NULL) } options = list(need_buffer = TRUE) catalog_apply(ctg, routine, .options = options) #> Error: A buffer greater than 0 is required to process the catalog. ``` -------------------------------- ### Example: Rasterize Canopy with Points-to-Raster Algorithm Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates basic usage of the `rasterize_canopy` function with the points-to-raster (`p2r`) method to create a canopy height model (CHM). This method assigns the highest point's height to each pixel. ```R LASfile <- system.file("extdata", "MixedConifer.laz", package="lidR") las <- readLAS(LASfile) col <- height.colors(50) # Example usage of p2r (points-to-raster) algorithm # chm <- rasterize_canopy(las, res = 0.5, p2r()) # plot(chm, col = col) ``` -------------------------------- ### Create and Manipulate LASheader Objects Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Demonstrates the creation of a LASheader object from data.frame, setting EPSG codes, and upgrading to LAS 1.4 format. It shows how to initialize a LAS object using the header and data. ```R data = data.frame(X = c(339002.889, 339002.983, 339002.918), Y = c(5248000.515, 5248000.478, 5248000.318), Z = c(975.589, 974.778, 974.471), gpstime = c(269347.28141, 269347.28142, 269347.28143), Intensity = c(82L, 54L, 27L), ReturnNumber = c(1L, 1L, 2L), NumberOfReturns = c(1L, 1L, 2L), ScanDirectionFlag = c(1L, 1L, 1L), EdgeOfFlightline = c(1L, 0L, 0L), Classification = c(1L, 1L, 1L), ScanAngleRank = c(-21L, -21L, -21L), UserData = c(32L, 32L, 32L), PointSourceID = c(17L, 17L, 17L)) header = LASheader(data) header # Record an EPSG code epsg(header) <- 32618 header las <- LAS(data, header) las # The function inferred a LAS 1.2 format 1 which is correct # Upgrade to LAS 1.4 for the example header@VLR <- list() # Erase VLR previously written header@PHB[["Global Encoding"]][["WKT"]] <- TRUE header@PHB[["Version Minor"]] <- 4L header@PHB[["Header Size"]] <- 375L header@PHB[["Offset to point data"]] <- 375L wkt(header) <- sf::st_crs("EPSG:32618")$wkt header las1.4 <- LAS(data, header) las1.4 ``` -------------------------------- ### Custom Metric Function Example Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Defines a sample R function to compute custom metrics (mean and max) for a given data vector. This function is designed to be applied within lidR's metric calculation functions. ```R f = function(x) {list(mean = mean(x), max = max(x))} ``` -------------------------------- ### Processing Options Configuration Source: https://cran.r-project.org/web/packages/lidR/refman/lidR Defines how sub-areas (chunks) are processed sequentially. Includes options for progress display, error handling, and engine control. ```APIDOC Processing Options: @processing_options: A list of options for sequential chunk processing. progress: boolean. Display a progress bar and chart. Default is TRUE. Can be enhanced by installing the 'progress' package. stop_early: boolean. Stop processing if an error occurs in a chunk. Default is TRUE. If FALSE, failed chunks are removed. wall.to.wall: logical. Controls internal checks to guarantee continuous output for wall-to-wall catalogs. If FALSE, controls are disabled and wall-to-wall outputs cannot be guaranteed. ``` -------------------------------- ### lidR: Performance and Compatibility Fixes (v4.1.1) Source: https://cran.r-project.org/web/packages/lidR/news/news Addresses issues with `readLAScatalog` when `raster` is not installed, performance degradation with `rasterize_terrain` due to `stars` package regression, and improves the speed of the local maximum filter. ```R readLAScatalog() rasterize_terrain() catalog_intersects(SpatExtent) lmf(fixed windows) ``` -------------------------------- ### Read and Display LAS Catalog Interactively Source: https://cran.r-project.org/web/packages/lidR/readme/README Manages and visualizes a collection of LAS/LAZ files using the `LAScatalog` object. `readLAScatalog` creates the catalog from a folder, and `plot` displays it on an interactive map, typically using the `mapview` package. ```R ctg <- readLAScatalog("") plot(ctg, map = TRUE) ```