|
|
|
if (!require(ForestTools)) install.packages("ForestTools") |
|
if (!require(terra)) install.packages("terra") |
|
if (!require(sf)) install.packages("sf") |
|
if (!require(imager)) install.packages("imager") |
|
|
|
|
|
library(ForestTools) |
|
library(terra) |
|
library(sf) |
|
library(imager) |
|
|
|
|
|
lin <- function(x) { x * 0.05 + 0.5 } |
|
|
|
chm_folder <- "/Users/taekim/ecohackathon/first_try_lidar/ForestTools/TryForestTools/first-flight/chm_tiles" |
|
|
|
|
|
tile_paths <- list.files(path = chm_folder, pattern = "\\.tif$", full.names = TRUE) |
|
print(tile_paths) |
|
|
|
crown_polygons_list <- list() |
|
|
|
for (chm_path in tile_paths) { |
|
|
|
chm <- terra::rast(chm_path) |
|
if (nlyr(chm) > 1) { |
|
chm <- chm[[1]] |
|
} |
|
|
|
|
|
ttops <- vwf(chm, winFun = lin, minHeight = 2) |
|
|
|
|
|
crowns_poly <- mcws(treetops = ttops, CHM = chm, format = "polygons", minHeight = 1.5) |
|
|
|
|
|
crown_polygons_list[[chm_path]] <- crowns_poly |
|
} |
|
|
|
|
|
all_crowns <- do.call(rbind, crown_polygons_list) |
|
|
|
|
|
merged_crowns <- st_union(all_crowns) |
|
|
|
|
|
merged_crowns[["area"]] <- st_area(merged_crowns) |
|
merged_crowns[["diameter"]] <- sqrt(merged_crowns[["area"]] / pi) * 2 |
|
|
|
|
|
st_write(merged_crowns, "path_to_save/merged_crown_polygons.shp") |
|
|
|
|
|
plot(merged_crowns$geometry, col = 'green', main = "Merged Crown Polygons") |
|
|
|
|