babypoby commited on
Commit
5d8dcba
·
1 Parent(s): ba479f7
Files changed (1) hide show
  1. TryForestTools/data.R +58 -0
TryForestTools/data.R ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Install the ForestTools package if it's not already installed
2
+ if (!require(ForestTools)) install.packages("ForestTools")
3
+ if (!require(terra)) install.packages("terra")
4
+ if (!require(sf)) install.packages("sf")
5
+ if (!require(imager)) install.packages("imager")
6
+
7
+ # Load the necessary libraries
8
+ library(ForestTools)
9
+ library(terra)
10
+ library(sf)
11
+ library(imager)
12
+
13
+ # Load sample canopy height model provided by ForestTools
14
+ chm_path <- "/Users/taekim/ecohackathon/first_try_lidar/ForestTools/TryForestTools/first-flight/chmtiles/chm_tile_1892_2880.tif"
15
+ if (file.exists(chm_path)) {
16
+ chm <- terra::rast(chm_path)
17
+ } else {
18
+ stop("CHM file does not exist")
19
+ }
20
+
21
+ # Check the CHM data
22
+ print("Summary of CHM:")
23
+ summary(chm)
24
+ print(paste("Number of NA values in CHM:", sum(is.na(values(chm)))))
25
+ plot(chm, main = "Canopy Height Model")
26
+
27
+ # Function for defining dynamic window size
28
+ lin <- function(x) { x * 0.05 + 0.6 }
29
+
30
+ # Detect treetops
31
+ ttops <- vwf(chm, winFun = lin, minHeight = 2)
32
+ print("Treetops detected:")
33
+ print(head(ttops))
34
+
35
+ # Plot CHM and treetops
36
+ plot(chm, xlab = "", ylab = "", xaxt = 'n', yaxt = 'n', main = "CHM with Treetops")
37
+ plot(ttops$geometry, col = "blue", pch = 20, cex = 0.5, add = TRUE)
38
+ print(paste("Mean height of treetops:", mean(ttops$height)))
39
+
40
+ # Create crown map
41
+ crowns_ras <- mcws(treetops = ttops, CHM = chm, minHeight = 1.5)
42
+
43
+ # Plot crowns
44
+ plot(crowns_ras, col = sample(rainbow(50), length(unique(values(crowns_ras))), replace = TRUE), legend = FALSE, xlab = "", ylab = "", xaxt = 'n', yaxt = 'n', main = "Crown Map")
45
+
46
+ # Create polygon crown map
47
+ crowns_poly <- mcws(treetops = ttops, CHM = chm, format = "polygons", minHeight = 1.5)
48
+ print("Crown polygons:")
49
+ print(head(crowns_poly))
50
+
51
+ # Plot CHM and crown outlines
52
+ plot(chm, xlab = "", ylab = "", xaxt = 'n', yaxt = 'n', main = "CHM with Crown Outlines")
53
+ plot(crowns_poly$geometry, border = "blue", lwd = 0.5, add = TRUE)
54
+
55
+ # Compute area and diameter
56
+ crowns_poly[["area"]] <- st_area(crowns_poly)
57
+ crowns_poly[["diameter"]] <- sqrt(crowns_poly[["area"]] / pi) * 2
58
+ print(paste("Mean crown diameter:", mean(crowns_poly$diameter)))