Repository navigation
Expand file tree
/
Copy pathPlot_Level_GLI_Tutorial.Rmd
More file actions
602 lines (477 loc) · 16.1 KB
/
Copy pathPlot_Level_GLI_Tutorial.Rmd
File metadata and controls
602 lines (477 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
---
title: "From RGB Pixels to Plot-Level Crop Traits"
subtitle: "A Self-Paced RGB Orthomosaic and Green Leaf Index Tutorial"
author: "Hands-On Remote Sensing and High-Throughput Phenotyping"
output:
learnr::tutorial:
progressive: true
allow_skip: true
runtime: shiny_prerendered
---
```{r setup, include=FALSE}
library(learnr)
library(shiny)
library(terra)
library(sf)
library(exactextractr)
options(width = 100)
terraOptions(progress = 0)
# learnr limits each exercise to 30 seconds by default.
# Raster calculations can require more time in Binder.
learnr::tutorial_options(
exercise.eval = FALSE,
exercise.timelimit = 300
)
# Resolve paths from the tutorial location instead of the RStudio working directory.
# Binder stores this project in /home/pawar, while RStudio may start in /home/rstudio.
# knitr::current_input() can return character(0) during the Shiny server phase.
# Build the candidate list without passing an empty path to normalizePath().
current_input_path <- tryCatch(
knitr::current_input(dir = TRUE),
error = function(e) character(0)
)
tutorial_candidates <- c(
"/home/pawar",
getwd()
)
if (length(current_input_path) == 1 && nzchar(current_input_path)) {
tutorial_candidates <- c(
tutorial_candidates,
dirname(
normalizePath(
current_input_path,
winslash = "/",
mustWork = FALSE
)
)
)
}
tutorial_candidates <- unique(tutorial_candidates)
tutorial_directory <- tutorial_candidates[
file.exists(file.path(tutorial_candidates, "data", "rgb_orthomosaic.tif")) &
file.exists(file.path(tutorial_candidates, "data", "plot_boundaries.geojson"))
][1]
if (is.na(tutorial_directory) || !nzchar(tutorial_directory)) {
stop(
"Could not locate the tutorial data folder. Expected data/rgb_orthomosaic.tif and data/plot_boundaries.geojson."
)
}
orthomosaic_path <- file.path(
tutorial_directory,
"data",
"rgb_orthomosaic.tif"
)
plots_path <- file.path(
tutorial_directory,
"data",
"plot_boundaries.geojson"
)
if (!file.exists(orthomosaic_path)) {
stop("Missing RGB orthomosaic: ", orthomosaic_path)
}
if (!file.exists(plots_path)) {
stop("Missing plot boundaries: ", plots_path)
}
output_directory <- file.path(tutorial_directory, "outputs")
dir.create(output_directory, showWarnings = FALSE, recursive = TRUE)
gli_path <- file.path(output_directory, "gli.tif")
threshold_path <- file.path(output_directory, "otsu_threshold.rds")
vegetation_mask_path <- file.path(output_directory, "vegetation_mask.tif")
vegetation_gli_path <- file.path(output_directory, "vegetation_gli.tif")
trait_table_path <- file.path(output_directory, "plot_level_rgb_gli_traits.csv")
rgb_raw <- terra::rast(orthomosaic_path)
plots_raw <- terra::vect(plots_path)
if (terra::nlyr(rgb_raw) < 3) stop("The RGB orthomosaic must contain at least three bands.")
rgb_raw <- rgb_raw[[1:3]]
names(rgb_raw) <- c("Red", "Green", "Blue")
plot_id_candidates <- c("plot_id", "Plot_ID", "plot", "Plot", "id", "ID")
plot_id_matches <- plot_id_candidates[plot_id_candidates %in% names(plots_raw)]
if (length(plot_id_matches) == 0) {
plots_raw$plot_id <- paste0("Plot_", seq_len(nrow(plots_raw)))
plot_id_field <- "plot_id"
} else {
plot_id_field <- plot_id_matches[[1]]
}
safe_gli <- function(red, green, blue) {
denominator <- 2 * green + red + blue
terra::ifel(denominator == 0, NA, (2 * green - red - blue) / denominator)
}
calculate_otsu_threshold <- function(raster, sample_size = 100000, bins = 256) {
sampled <- terra::spatSample(
raster,
size = min(sample_size, terra::ncell(raster)),
method = "regular",
na.rm = TRUE,
values = TRUE
)
values <- as.numeric(sampled[, 1])
values <- values[is.finite(values)]
if (length(values) < 2) stop("Not enough valid GLI values for Otsu thresholding.")
h <- hist(values, breaks = bins, plot = FALSE)
p <- h$counts / sum(h$counts)
omega <- cumsum(p)
mu <- cumsum(p * h$mids)
mu_total <- sum(p * h$mids)
variance <- (mu_total * omega - mu)^2 / (omega * (1 - omega))
variance[!is.finite(variance)] <- NA_real_
h$mids[which.max(variance)]
}
align_plots <- function(raster, polygons) {
if (!terra::same.crs(raster, polygons)) {
polygons <- terra::project(polygons, terra::crs(raster))
}
polygons
}
```
## Welcome
This tutorial uses simple exercise chunks that work in both `learnr` and the RStudio Console. All outputs use standard R plots and printed tables. There are no interactive raster maps, vector maps, Plotly charts, or interactive tables.
### Learning objectives
1. Inspect an RGB orthomosaic.
2. Name Red, Green, and Blue bands.
3. Calculate the Green Leaf Index (GLI).
4. Apply Otsu thresholding.
5. Create a vegetation mask.
6. Mask RGB and GLI layers.
7. Overlay plot polygons using a standard R plot.
8. Extract plot-level mean GLI, GLI variability, and canopy cover.
9. Export the plot-level trait table as a CSV file.
> The expected band order is Red, Green, Blue.
---
## Activity 1: Inspect the RGB orthomosaic
```{r inspect-raster, exercise=TRUE}
rgb <- rgb_raw
print(rgb)
terra::nlyr(rgb)
terra::res(rgb)
terra::ext(rgb)
terra::crs(rgb)
```
---
## Activity 2: Display the RGB composite
```{r rgb-composite, exercise=TRUE}
rgb <- rgb_raw
terra::plotRGB(
rgb,
r = 1,
g = 2,
b = 3,
stretch = "lin",
main = "RGB True-Color Orthomosaic"
)
```
---
## Activity 3: Name and compare RGB bands
```{r compare-bands, exercise=TRUE}
rgb <- rgb_raw
names(rgb) <- c("Red", "Green", "Blue")
par(mfrow = c(1, 3))
plot(rgb[["Red"]], col = hcl.colors(100, "Reds"), main = "Red band")
plot(rgb[["Green"]], col = hcl.colors(100, "Greens"), main = "Green band")
plot(rgb[["Blue"]], col = hcl.colors(100, "Blues"), main = "Blue band")
par(mfrow = c(1, 1))
```
---
## Activity 4: Calculate and save GLI
```{r calculate-gli, exercise=TRUE, exercise.timelimit=300}
rgb <- rgb_raw
red <- rgb[["Red"]]
green <- rgb[["Green"]]
blue <- rgb[["Blue"]]
denominator <- 2 * green + red + blue
gli <- terra::ifel(
denominator == 0,
NA,
(2 * green - red - blue) / denominator
)
names(gli) <- "GLI"
terra::writeRaster(gli, gli_path, overwrite = TRUE)
plot(gli, col = hcl.colors(100, "RdYlGn"), main = "Green Leaf Index")
terra::global(gli, c("min", "mean", "max"), na.rm = TRUE)
cat("GLI saved to:", gli_path, "\n")
```
### GLI histogram
```{r gli-histogram, exercise=TRUE, exercise.timelimit=300}
if (!file.exists(gli_path)) stop("Run Activity 4 first. GLI file is missing.")
gli <- terra::rast(gli_path)
gli_values <- terra::values(gli, mat = FALSE)
gli_values <- gli_values[is.finite(gli_values)]
hist(gli_values, breaks = 80, col = "grey80", border = "white", main = "GLI Distribution", xlab = "GLI")
```
---
## Activity 5: Calculate and save the Otsu threshold
```{r otsu-threshold, exercise=TRUE, exercise.timelimit=300}
if (!file.exists(gli_path)) stop("Run Activity 4 first. GLI file is missing.")
gli <- terra::rast(gli_path)
otsu_threshold <- calculate_otsu_threshold(gli)
saveRDS(otsu_threshold, threshold_path)
cat("Otsu GLI threshold:", round(otsu_threshold, 4), "\n")
values <- terra::values(gli, mat = FALSE)
values <- values[is.finite(values)]
hist(values, breaks = 80, main = "GLI and Otsu Threshold", xlab = "GLI")
abline(v = otsu_threshold, col = "red", lwd = 3, lty = 2)
cat("Threshold saved to:", threshold_path, "\n")
```
---
## Activity 6: Create and save the vegetation mask
```{r vegetation-mask, exercise=TRUE, exercise.timelimit=300}
if (!file.exists(gli_path)) stop("Run Activity 4 first. GLI file is missing.")
if (!file.exists(threshold_path)) stop("Run Activity 5 first. Threshold file is missing.")
gli <- terra::rast(gli_path)
otsu_threshold <- readRDS(threshold_path)
vegetation_mask <- terra::ifel(gli > otsu_threshold, 1, 0)
names(vegetation_mask) <- "Vegetation_Mask"
terra::writeRaster(vegetation_mask, vegetation_mask_path, overwrite = TRUE, datatype = "INT1U")
plot(vegetation_mask, col = c("grey85", "forestgreen"), main = "Binary Vegetation Mask")
cat("Vegetation mask saved to:", vegetation_mask_path, "\n")
```
---
## Activity 7: Create and save vegetation-only GLI
```{r vegetation-gli, exercise=TRUE, exercise.timelimit=300}
if (!file.exists(gli_path)) stop("Run Activity 4 first. GLI file is missing.")
if (!file.exists(vegetation_mask_path)) stop("Run Activity 6 first. Vegetation mask is missing.")
gli <- terra::rast(gli_path)
vegetation_mask <- terra::rast(vegetation_mask_path)
vegetation_gli <- terra::ifel(vegetation_mask == 1, gli, NA)
names(vegetation_gli) <- "Vegetation_GLI"
terra::writeRaster(vegetation_gli, vegetation_gli_path, overwrite = TRUE)
plot(vegetation_gli, col = hcl.colors(100, "YlGn"), main = "Vegetation-Only GLI")
cat("Vegetation-only GLI saved to:", vegetation_gli_path, "\n")
```
---
## Activity 8: Inspect and plot vector plots with IDs
Inspect the plot vector data, examine its attributes and coordinate reference system (CRS), and visualize the polygons with their `plot_id` labels.
### Step 1: Inspect the vector data
```{r inspect-vector, exercise=TRUE, exercise.timelimit=300}
if (!exists("plots_raw")) stop("Plot vector data are missing.")
# Inspect the vector object
print(plots_raw)
# Inspect attribute names and records
names(plots_raw)
head(as.data.frame(plots_raw))
# Check geometry type, feature count, and CRS
terra::geomtype(plots_raw)
nrow(plots_raw)
terra::crs(plots_raw)
# Check for plot_id
if (!"plot_id" %in% names(plots_raw)) {
stop("The plot_id attribute is missing.")
}
```
### Step 2: Plot vector polygons with plot_id labels
```{r plot-vector-labels, exercise=TRUE, exercise.timelimit=300}
# Plot the vector polygons
plot(
plots_raw,
col = "lightgreen",
border = "darkgreen",
main = "Study Plots with Plot IDs"
)
# Calculate label positions inside polygons
label_points <- terra::centroids(plots_raw, inside = TRUE)
# Extract label coordinates
coords <- terra::crds(label_points)
# Add plot_id labels
text(
x = coords[, 1],
y = coords[, 2],
labels = plots_raw$plot_id,
cex = 0.8,
font = 2
)
```
### Questions
1. How many plots are present in the dataset?
2. What information is stored in the `plot_id`, `Range`, and `Row` attributes?
3. Why should we inspect vector data before overlaying it on a raster?
---
---
## Activity 9: Overlay plot boundaries
```{r plot-overlay, exercise=TRUE, exercise.timelimit=300}
if (!file.exists(vegetation_gli_path)) stop("Run Activity 7 first. Vegetation GLI is missing.")
vegetation_gli <- terra::rast(vegetation_gli_path)
plots <- align_plots(vegetation_gli, plots_raw)
plot(vegetation_gli, col = hcl.colors(100, "YlGn"), main = "Vegetation GLI with Plot Boundaries")
plot(plots, add = TRUE, border = "black", lwd = 1.5)
```
---
## Activity 10: Extract and save plot-level traits
This activity reads the saved raster outputs. GLI is not recalculated.
```{r extract-traits, exercise=TRUE, exercise.timelimit=600}
if (!file.exists(vegetation_gli_path)) stop("Run Activity 7 first. Vegetation GLI is missing.")
if (!file.exists(vegetation_mask_path)) stop("Run Activity 6 first. Vegetation mask is missing.")
vegetation_gli <- terra::rast(vegetation_gli_path)
vegetation_mask <- terra::rast(vegetation_mask_path)
plots <- align_plots(vegetation_gli, plots_raw)
# exactextractr uses fractional pixel coverage at plot boundaries.
plots_sf <- sf::st_as_sf(plots)
vegetation_gli_stats <- exactextractr::exact_extract(
vegetation_gli,
plots_sf,
fun = c("mean", "stdev"),
progress = FALSE
)
canopy_cover_stats <- exactextractr::exact_extract(
vegetation_mask,
plots_sf,
fun = "mean",
progress = FALSE
)
plot_level_traits <- data.frame(
plot_id = plots_sf[[plot_id_field]],
mean_vegetation_gli = round(vegetation_gli_stats$mean, 4),
sd_vegetation_gli = round(vegetation_gli_stats$stdev, 4),
canopy_cover_percent = round(100 * canopy_cover_stats, 2)
)
write.csv(plot_level_traits, trait_table_path, row.names = FALSE, na = "")
print(plot_level_traits)
cat("Trait table saved to:", trait_table_path, "\n")
```
---
## Activity 11: Mean Vegetation GLI Heatmap
In this activity, visualize mean vegetation GLI for each study plot by overlaying transparent colors on the RGB orthomosaic.
```{r activity-10-gli-heatmap, exercise=TRUE, exercise.timelimit=300}
if (!file.exists(trait_table_path)) {
stop("Run the plot-level trait extraction activity first.")
}
plot_level_traits <- read.csv(trait_table_path, stringsAsFactors = FALSE)
# Align polygons with the RGB raster
plots_aligned <- align_plots(rgb_raw, plots_raw)
plots_sf <- sf::st_as_sf(plots_aligned)
plots_sf$plot_id <- as.character(plots_sf[[plot_id_field]])
plot_level_traits$plot_id <- as.character(plot_level_traits$plot_id)
plots_heatmap <- merge(
plots_sf,
plot_level_traits[, c("plot_id", "mean_vegetation_gli")],
by = "plot_id",
all.x = TRUE,
sort = FALSE
)
gli <- plots_heatmap$mean_vegetation_gli
if (all(is.na(gli))) stop("No matching mean GLI values found.")
gli_range <- range(gli, na.rm = TRUE)
heat_cols <- hcl.colors(100, "YlGn")
bin <- rep(NA_integer_, length(gli))
valid <- !is.na(gli)
if (diff(gli_range) > 0) {
bin[valid] <- cut(
gli[valid],
breaks = seq(gli_range[1], gli_range[2], length.out = 101),
include.lowest = TRUE,
labels = FALSE
)
} else {
bin[valid] <- 50
}
# Reserve space on the right for the legend
par(mar = c(4, 4, 4, 8), xpd = NA)
terra::plotRGB(
rgb_raw,
r = 1, g = 2, b = 3,
stretch = "lin",
main = "Mean Vegetation GLI by Plot"
)
plot(
sf::st_geometry(plots_heatmap),
add = TRUE,
col = grDevices::adjustcolor(heat_cols[bin], alpha.f = 0.60),
border = "white",
lwd = 1
)
# Label each plot with its mean GLI
label_points <- sf::st_point_on_surface(plots_heatmap)
coords <- sf::st_coordinates(label_points)
text(
coords[, 1], coords[, 2],
labels = ifelse(valid, sprintf("%.3f", gli), "NA"),
cex = 0.8,
font = 2,
col = "black"
)
# Legend on the right
legend(
"right",
inset = c(-0.28, 0),
legend = sprintf("%.3f", seq(gli_range[1], gli_range[2], length.out = 5)),
fill = heat_cols[round(seq(1, 100, length.out = 5))],
title = "Mean GLI",
bty = "n",
cex = 0.8
)
par(mar = c(5.1, 4.1, 4.1, 2.1), xpd = FALSE)
```
## Activity 12: Canopy Cover Heatmap
```{r activity-11-canopy-heatmap, exercise=TRUE, exercise.timelimit=300}
if (!file.exists(trait_table_path)) {
stop("Run the plot-level trait extraction activity first.")
}
plot_level_traits <- read.csv(trait_table_path, stringsAsFactors = FALSE)
# Align polygons with the RGB raster
plots_aligned <- align_plots(rgb_raw, plots_raw)
plots_sf <- sf::st_as_sf(plots_aligned)
plots_sf$plot_id <- as.character(plots_sf[[plot_id_field]])
plot_level_traits$plot_id <- as.character(plot_level_traits$plot_id)
plots_heatmap <- merge(
plots_sf,
plot_level_traits[, c("plot_id", "canopy_cover_percent")],
by = "plot_id",
all.x = TRUE,
sort = FALSE
)
canopy <- plots_heatmap$canopy_cover_percent
if (all(is.na(canopy))) stop("No matching canopy cover values found.")
canopy_range <- range(canopy, na.rm = TRUE)
heat_cols <- hcl.colors(100, "Greens")
bin <- rep(NA_integer_, length(canopy))
valid <- !is.na(canopy)
if (diff(canopy_range) > 0) {
bin[valid] <- cut(
canopy[valid],
breaks = seq(canopy_range[1], canopy_range[2], length.out = 101),
include.lowest = TRUE,
labels = FALSE
)
} else {
bin[valid] <- 50
}
# Reserve space on the right for the legend
par(mar = c(4, 4, 4, 8), xpd = NA)
terra::plotRGB(
rgb_raw,
r = 1, g = 2, b = 3,
stretch = "lin",
main = "Canopy Cover by Plot"
)
plot(
sf::st_geometry(plots_heatmap),
add = TRUE,
col = grDevices::adjustcolor(heat_cols[bin], alpha.f = 0.60),
border = "white",
lwd = 1
)
# Label each plot with canopy cover percentage
label_points <- sf::st_point_on_surface(plots_heatmap)
coords <- sf::st_coordinates(label_points)
text(
coords[, 1], coords[, 2],
labels = ifelse(valid, sprintf("%.1f%%", canopy), "NA"),
cex = 0.8,
font = 2,
col = "black"
)
# Legend on the right
legend(
"right",
inset = c(-0.28, 0),
legend = paste0(
round(seq(canopy_range[1], canopy_range[2], length.out = 5), 1),
"%"
),
fill = heat_cols[round(seq(1, 100, length.out = 5))],
title = "Canopy cover",
bty = "n",
cex = 0.8
)
par(mar = c(5.1, 4.1, 4.1, 2.1), xpd = FALSE)
```
## Workflow complete
Intermediate outputs are saved in the outputs folder and reused by later activities.