-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils_mosaic.R
3924 lines (3755 loc) · 145 KB
/
utils_mosaic.R
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
validate_and_replicate <- function(argument, created_shapes, verbose = TRUE) {
if ((length(argument) != length(created_shapes)) & verbose) {
warning(paste0("`", deparse(substitute(argument)), "` must have length 1 or ", length(created_shapes), " (the number of drawn polygons)."), call. = FALSE)
}
if (length(argument) == 1 & length(created_shapes) != 1) {
argument <- rep(argument, length(created_shapes))
}
return(argument)
}
validate_and_replicate2 <- function(argument, created_shapes, verbose = TRUE) {
if ((!is.null(argument) & (length(argument) != nrow(created_shapes))) & verbose) {
warning(paste0("`", deparse(substitute(argument)), "` must have length 1 or ", nrow(created_shapes), " (the number of drawn polygons)."), call. = FALSE)
}
if (length(argument) == 1 & nrow(created_shapes) != 1) {
argument <- rep(argument, nrow(created_shapes))
}
return(argument)
}
sf_to_polygon <- function(shps) {
if(inherits(shps, "list")){
shps <- do.call(rbind, shps)
}
classes <- sapply(lapply(sf::st_geometry(shps$geometry), class), function(x){x[2]})
shps[classes %in% c("POINT", "LINESTRING"), ] <-
shps[classes %in% c("POINT", "LINESTRING"), ] |>
sf::st_buffer(0.0000001) |>
sf::st_cast("POLYGON") |>
sf::st_simplify(preserveTopology = TRUE)
return(shps)
}
find_aggrfact <- function(mosaic, max_pixels = 1000000){
compute_downsample <- function(nr, nc, n) {
if (n == 0) {
invisible(nr * nc)
} else if (n == 1) {
invisible(ceiling(nr/2) * ceiling(nc/2))
} else if (n > 1) {
invisible(ceiling(nr/(n+1)) * ceiling(nc/(n+1)))
} else {
stop("Invalid downsampling factor. n must be a non-negative integer.")
}
}
nr <- nrow(mosaic)
nc <- ncol(mosaic)
npixel <- nr * nc
possible_downsamples <- 0:20
possible_npix <- sapply(possible_downsamples, function(x){
compute_downsample(nr, nc, x)
})
downsample <- which.min(abs(possible_npix - max_pixels))
downsample <- ifelse(downsample == 1, 0, downsample)
return(downsample)
}
compute_measures_mosaic <- function(contour){
lw <- help_lw(contour)
cdist <- help_centdist(contour)
data.frame(area = help_area(contour),
perimeter = sum(help_distpts(contour)),
length = lw[[1]],
width = lw[[2]],
diam_min = min(cdist) * 2,
diam_mean = mean(cdist) * 2,
diam_max = max(cdist) * 2)
}
compute_dists <- function(subset_coords, direction = c("horizontal", "vertical")){
optdirec <- c("horizontal", "vertical")
optdirec <- pmatch(direction[[1]], optdirec)
n <- nrow(subset_coords)
subset_coords <- subset_coords |> dplyr::select(x, y) |> as.data.frame()
nearest <- order(subset_coords[, optdirec])
subset_distances <- numeric(n - 1)
for (j in 1:(n - 1)) {
x1 <- subset_coords[nearest[j], 1]
y1 <- subset_coords[nearest[j], 2]
x2 <- subset_coords[nearest[j+1], 1]
y2 <- subset_coords[nearest[j+1], 2]
distance <- sqrt((x2 - x1)^2 + (y2 - y1)^2)
subset_distances[j] <- distance
}
subset_distances
}
linear_iterpolation <- function(mosaic, points, method = "loess"){
if(inherits(points, "list")){
points <- do.call(rbind, points)
}
xy <- sf::st_coordinates(points)[, 1:2]
vals <- terra::values(mosaic)[terra::cellFromXY(mosaic, xy), ]
vals <- data.frame(cbind(xy, vals))
names(vals) <- c("x", "y", "z")
newdata <- as.data.frame(terra::xyFromCell(mosaic, 1:terra::ncell(mosaic)))
new_ras <-
terra::rast(
lapply(3:ncol(vals), function(i){
if(method == "loess"){
mod <- loess(vals[, i] ~ x + y, data = vals)
} else{
mod <- lm(vals[, i] ~ x + y, data = vals)
}
terra::rast(matrix(predict(mod, newdata = newdata),
nrow = nrow(mosaic),
ncol = ncol(mosaic),
byrow = TRUE))
})
)
terra::crs(new_ras) <- terra::crs(mosaic)
terra::ext(new_ras) <- terra::ext(mosaic)
terra::resample(new_ras, mosaic)
}
idw_interpolation <- function(mosaic, points){
downsample <- find_aggrfact(mosaic, max_pixels = 200000)
if(downsample > 0){
magg <- mosaic_aggregate(mosaic, pct = round(100 / downsample))
} else{
magg <- mosaic
}
if(inherits(points, "list")){
points <- do.call(rbind, points)
}
xy <- sf::st_coordinates(points)[, 1:2]
vals <- terra::values(magg)[terra::cellFromXY(magg, xy), ]
vals <- data.frame(cbind(xy, vals))
xy_grid <- terra::xyFromCell(magg, 1:terra::ncell(magg))
newx <- seq(min(xy_grid[,1]), max(xy_grid[,1]), length.out = 1000)
newy <- seq(min(xy_grid[,2]), max(xy_grid[,2]), length.out = 1000)
new_ras <-
terra::rast(
lapply(3:ncol(vals), function(i){
interp <- idw_interpolation_cpp(vals[, 1], vals[, 2], vals[, i], xy_grid[, 1], xy_grid[, 2])
ra3 <-
terra::rast(matrix(interp,
nrow = nrow(magg),
ncol = ncol(magg),
byrow = TRUE))
})
)
terra::crs(new_ras) <- terra::crs(mosaic)
terra::ext(new_ras) <- terra::ext(mosaic)
terra::resample(new_ras, mosaic)
}
# Helper function to check and align DSM with mosaic
align_dsm <- function(dsm, mosaic) {
# Check if extent, resolution, and CRS match
if (!terra::ext(dsm) == terra::ext(mosaic) ||
!all(terra::res(dsm) == terra::res(mosaic)) ||
!terra::crs(dsm) == terra::crs(mosaic)) {
message("Adjusting DSM to match mosaic extent, resolution, and CRS.")
# Align DSM to match the mosaic properties
dsm <- terra::resample(dsm, mosaic, method = "lanczos")
}
return(dsm)
}
#' Mosaic interpolation
#'
#' Performs the interpolation of points from a raster object.
#'
#' @param mosaic An `SpatRaster` object
#' @param points An `sf` object with the points for x and y coordinates, usually
#' obtained with [shapefile_build()]. Alternatively, an external shapefile
#' imported with [shapefile_input()] containing the x and y coordinates can be
#' used. The function will handle most used shapefile formats (eg.,
#' .shp, .rds) and convert the imported shapefile to an sf object.
#' @param method One of "bilinear" (default), "loess" (local regression) or
#' "idw" (Inverse Distance Weighting).
#' @importFrom stats loess
#'
#' @return An `SpatRaster` object with the same extend and crs from `mosaic`
#' @export
#'
mosaic_interpolate <- function(mosaic, points, method = c("bilinear", "loess", "idw")){
if(terra::crs(points) != terra::crs(mosaic)){
terra::crs(points) <- terra::crs(mosaic)
}
if(!method[[1]] %in% c("bilinear", "idw", "loess")){
stop("'method' must be one of 'bilinear', 'loess', or 'idw'")
}
if(method[[1]] %in% c("bilinear", "loess")){
linear_iterpolation(mosaic, points, method = method[[1]])
} else{
idw_interpolation(mosaic, points)
}
}
#' Analyze a mosaic of remote sensing data
#'
#' This function analyzes a mosaic of remote sensing data (UVAs or satellite
#' imagery), extracting information from specified regions of interest (ROIs)
#' defined in a shapefile or interactively drawn on the mosaic. It allows
#' counting and measuring individuals (eg., plants), computing canopy coverage,
#' and statistical summaries (eg., mean, coefficient of variation) for
#' vegetation indices (eg, NDVI) at a block, plot, individual levels or even
#' extract the raw results at pixel level.
#'
#' @details
#' Since multiple blocks can be analyzed, the length of arguments `grid`,
#' `nrow`, `ncol`, `buffer_edge`, , `buffer_col`, `buffer_row`, `segment_plot`,
#' `segment_i, ndividuals`, `includ_if`, `threshold`, `segment_index`, `invert`,
#' `filter`, `threshold`, `lower_size`, `upper_size`, `watershed`, and
#' `lower_noise`, can be either an scalar (the same argument applied to all the
#' drawn blocks), or a vector with the same length as the number of drawn. In
#' the last, each block can be analyzed with different arguments.
#'
#' When `segment_individuals = TRUE` is enabled, individuals are included within
#' each plot based on the `include_if` argument. The default value
#' (`'centroid'`) includes an object in a given plot if the centroid of that
#' object is within the plot. This makes the inclusion mutually exclusive (i.e.,
#' an individual is included in only one plot). If `'covered'` is selected,
#' objects are included only if their entire area is covered by the plot. On the
#' other hand, selecting `overlap` is the complement of `covered`; in other
#' words, objects that overlap the plot boundary are included. Finally, when
#' `intersect` is chosen, objects that intersect the plot boundary are included.
#' This makes the inclusion ambiguous (i.e., an object can be included in more
#' than one plot).
#'
#' @inheritParams mosaic_view
#' @inheritParams analyze_objects
#' @inheritParams image_binary
#' @inheritParams plot_id
#' @param r,g,b,re,nir,swir,tir The red, green, blue, red-edge, near-infrared,
#' shortwave Infrared, and thermal infrared bands of the image, respectively.
#' By default, the function assumes a BGR as input (b = 1, g = 2, r = 3). If a
#' multispectral image is provided up to seven bands can be used to compute
#' built-in indexes. There are no limitation of band numbers if the index is
#' computed using the band name.
#' @param crop_to_shape_ext Crop the mosaic to the extension of shapefile?
#' Defaults to `TRUE`. This allows for a faster index computation when the
#' region of the built shapefile is much smaller than the entire mosaic
#' extension.
#' @param grid Logical, indicating whether to use a grid for segmentation
#' (default: TRUE).
#' @param nrow Number of rows for the grid (default: 1).
#' @param ncol Number of columns for the grid (default: 1).
#' @param plot_width,plot_height The width and height of the plot shape (in the
#' mosaic unit). It is mutually exclusiv with `buffer_col` and `buffer_row`.
#' @param indexes An optional `SpatRaster` object with the image indexes,
#' computed with [mosaic_index()].
#' @param shapefile An optional shapefile containing regions of interest (ROIs)
#' for analysis.
#' @param basemap An optional basemap generated with [mosaic_view()].
#' @param build_shapefile Logical, indicating whether to interactively draw ROIs
#' if the shapefile is `NULL` (default: TRUE).
#' @param check_shapefile Logical, indicating whether to validate the shapefile
#' with an interactive map view (default: TRUE). This enables live editing of
#' the drawn shapefile by deleting or changing the drawn grids.
#' @param buffer_edge Width of the buffer around the shapefile (default: 5).
#' @param buffer_col,buffer_row Buffering factor for the columns and rows,
#' respectively, of each individual plot's side. A value between 0 and 0.5
#' where 0 means no buffering and 0.5 means complete buffering (default: 0). A
#' value of 0.25 will buffer the plot by 25% on each side.
#' @param segment_plot Logical, indicating whether to segment plots (default:
#' FALSE). If `TRUE`, the `segment_index` will be computed, and pixels with
#' values below the `threshold` will be selected.
#' @param segment_individuals Logical, indicating whether to segment individuals
#' within plots (default: FALSE). If `TRUE`, the `segment_index` will be
#' computed, and pixels with values below the `threshold` will be selected, and
#' a watershed-based segmentation will be performed.
#' @param segment_pick When `segment_plot` or `segment_individuals` are `TRUE`,
#' `segment_pick` allows segmenting background (eg., soil) and foreground
#' (eg., plants) interactively by picking samples from background and
#' foreground using [mosaic_segment_pick()]
#' @param mask An optional mask (SpatRaster) to mask the mosaic.
#' @param dsm A SpatRaster object representing the digital surface model. Must
#' be a single-layer raster. If a DSM is informed, a mask will be derived from
#' it using [mosaic_chm_mask()].
#' @param dsm_lower A numeric value specifying the lower height threshold. All
#' heights greater than this value are retained.
#' @param dsm_upper An optional numeric value specifying the upper height
#' threshold. If provided, only heights between lower and upper are retained.
#' @param dsm_window_size An integer (meters) specifying the window size (rows
#' and columns, respectively) for creating a DTM using a moving window.
#' Default is c(5, 5).
#' @param simplify Removes vertices in polygons to form simpler shapes. The
#' function implementation uses the Douglas–Peucker algorithm using
#' [sf::st_simplify()] for simplification.
#' @param map_individuals If `TRUE`, the distance between objects within plots
#' is computed. The distance can be mapped either in the horizontal or vertical
#' direction. The distances, coefficient of variation (CV), and mean of
#' distances are then returned.
#' @param map_direction The direction for mapping individuals within plots.
#' Should be one of `"horizontal"` or `"vertical"` (default).
#' @param watershed If `TRUE` (default), performs watershed-based object
#' detection. This will detect objects even when they are touching one another.
#' If FALSE, all pixels for each connected set of foreground pixels are set to
#' a unique object. This is faster but is not able to segment touching
#' objects.
#' @param tolerance The minimum height of the object in the units of image
#' intensity between its highest point (seed) and the point where it contacts
#' another object (checked for every contact pixel). If the height is smaller
#' than the tolerance, the object will be combined with one of its neighbors,
#' which is the highest.
#' @param extension Radius of the neighborhood in pixels for the detection of
#' neighboring objects. A higher value smooths out small objects.
#' @param include_if Character vector specifying the type of intersection.
#' Defaults to "centroid" (individuals in which the centroid is included within
#' the drawn plot will be included in that plot). Other possible values include
#' `"covered"`, `"overlap"`, and `"intersect"`. See Details for a detailed
#' explanation of these intersecting controls.
#' @param plot_index The index(es) to be computed for the drawn plots. Either a
#' single vegetation index (e.g., `"GLAI"`), a vector of indexes (e.g.,
#' `c("GLAI", "NGRDI", "HUE")`), or a custom index based on the available
#' bands (e.g., `"(R-B)/(R+B)"`). See [pliman_indexes()] and [image_index()]
#' for more details.
#' @param segment_index The index used for segmentation. The same rule as
#' `plot_index`. Defaults to `NULL`
#' @param threshold By default (threshold = "Otsu"), a threshold value based on
#' Otsu's method is used to reduce the grayscale image to a binary image. If a
#' numeric value is provided, this value will be used as a threshold.
#' @param summarize_fun The function to compute summaries for the pixel values.
#' Defaults to "mean," i.e., the mean value of the pixels (either at a plot- or
#' individual-level) is returned.
#' @param summarize_quantiles quantiles to be computed when 'quantile' is on `summarize_fun`.
#' @param attribute The attribute to be shown at the plot when `plot` is `TRUE`. Defaults to the first `summary_fun` and first `segment_index`.
#' @param invert Logical, indicating whether to invert the mask. Defaults to
#' `FALSE`, i.e., pixels with intensity greater than the threshold values are
#' selected.
#' @param color_regions The color palette for regions (default:
#' rev(grDevices::terrain.colors(50))).
#' @param plot Logical, indicating whether to generate plots (default: TRUE).
#' @param verbose Logical, indicating whether to display verbose output
#' (default: TRUE).
#'
#' @return A list containing the following objects:
#' * `result_plot`: The results at a plot level.
#' * `result_plot_summ`: The summary of results at a plot level. When
#' `segment_individuals = TRUE`, the number of individuals, canopy coverage,
#' and mean values of some shape statistics such as perimeter, length, width,
#' and diameter are computed.
#' * `result_individ`: The results at an individual level.
#' * `map_plot`: An object of class `mapview` showing the plot-level results.
#' * `map_individual`: An object of class `mapview` showing the individual-level
#' results.
#' * `shapefile`: The generated shapefile, with the drawn grids/blocks.
#' @export
#'
#' @examples
#' if (interactive() && requireNamespace("EBImage")) {
#' library(pliman)
#' url <- "https://github.com/TiagoOlivoto/images/raw/master/pliman/rice_field/rice_ex.tif"
#' mosaic <- mosaic_input(url)
#' # Draw a polygon (top left, top right, bottom right, bottom left, top left)
#' # include 8 rice lines and one column
#'res <-
#' mosaic_analyze(mosaic,
#' r = 1, g = 2, b = 3,
#' segment_individuals = TRUE, # segment the individuals
#' segment_index = "(G-B)/(G+B-R)",# index for segmentation
#' filter = 4,
#' nrow = 8,
#' map_individuals = TRUE)
#'# map with individual results
#'res$map_indiv
#' }
mosaic_analyze <- function(mosaic,
r = 3,
g = 2,
b = 1,
re = NA,
nir = NA,
swir = NA,
tir = NA,
crop_to_shape_ext = TRUE,
grid = TRUE,
nrow = 1,
ncol = 1,
plot_width = NULL,
plot_height = NULL,
layout = "lrtb",
indexes = NULL,
shapefile = NULL,
basemap = NULL,
build_shapefile = TRUE,
check_shapefile = TRUE,
buffer_edge = 1,
buffer_col = 0,
buffer_row = 0,
segment_plot = FALSE,
segment_individuals = FALSE,
segment_pick = FALSE,
mask = NULL,
dsm = NULL,
dsm_lower = 0.2,
dsm_upper = NULL,
dsm_window_size = c(5, 5),
simplify = FALSE,
map_individuals = FALSE,
map_direction = c("horizontal", "vertical"),
watershed = TRUE,
tolerance = 1,
extension = 1,
include_if = "centroid",
plot_index = "GLI",
segment_index = NULL,
threshold = "Otsu",
opening = FALSE,
closing = FALSE,
filter = FALSE,
erode = FALSE,
dilate = FALSE,
lower_noise = 0.15,
lower_size = NULL,
upper_size = NULL,
topn_lower = NULL,
topn_upper = NULL,
summarize_fun = "mean",
summarize_quantiles = NULL,
attribute = NULL,
invert = FALSE,
color_regions = rev(grDevices::terrain.colors(50)),
alpha = 1,
max_pixels = 2e6,
downsample = NULL,
quantiles = c(0, 1),
plot = TRUE,
verbose = TRUE){
if(!is.null(dsm)){
dsm <- align_dsm(dsm, mosaic)
if(verbose){
message("\014","\nCreating the mask based on the digital surface model...\n")
}
mask <- mosaic_chm_mask(dsm, lower = dsm_lower, upper = dsm_upper, window_size = dsm_window_size)
}
includeopt <- c("intersect", "covered", "overlap", "centroid")
includeopt <- includeopt[sapply(include_if, function(x){pmatch(x, includeopt)})]
if(is.null(plot_index) & !is.null(segment_index)){
plot_index <- segment_index
}
if(!is.null(indexes)){
if(!inherits(indexes, "SpatRaster")){
stop("Object `indexes` must be an object of class `SpatRaster`.")
} else{
plot_index <- names(indexes)
}
}
if(!is.null(plot_index) & is.null(segment_index)){
segment_index <- plot_index[[1]]
}
if(any(segment_individuals) | any(segment_plot) & !is.null(plot_index) & !segment_index %in% plot_index){
plot_index <- unique(append(plot_index, segment_index))
}
if(is.null(attribute)){
attribute <- paste(summarize_fun[[1]], segment_index[[1]], sep = ".")
}
if(terra::crs(mosaic) == ""){
terra::crs(mosaic) <- terra::crs("EPSG:4326")
}
nlyrs <- terra::nlyr(mosaic)
if(verbose){
message("\014","\nBuilding the mosaic...\n")
}
if(is.null(basemap)){
basemap <-
suppressWarnings(
mosaic_view(mosaic,
r = r,
g = g,
b = b,
re = re,
nir = nir,
swir = swir,
tir = tir,
max_pixels = max_pixels,
verbose = verbose,
downsample = downsample,
quantiles = quantiles,
edit = FALSE)
)
}
if(is.null(shapefile)){
created_shapes <-
suppressWarnings(
shapefile_build(mosaic,
basemap = basemap,
grid = grid,
nrow = nrow,
ncol = ncol,
plot_width = plot_width,
plot_height = plot_height,
layout = layout,
build_shapefile = build_shapefile,
check_shapefile = check_shapefile,
sf_to_polygon = TRUE,
buffer_edge = buffer_edge,
buffer_col = buffer_col,
buffer_row = buffer_row,
max_pixels = max_pixels,
verbose = verbose,
downsample = downsample,
quantiles = quantiles)
)
# crop to the analyzed area
if(crop_to_shape_ext){
ress <- terra::res(mosaic)
if(sum(ress) != 2){
poly_ext <-
do.call(rbind, lapply(created_shapes, function(x){
x
})) |>
sf::st_transform(crs = sf::st_crs(terra::crs(mosaic))) |>
terra::vect() |>
terra::buffer(buffer_edge) |>
terra::ext()
} else{
poly_ext <-
do.call(rbind, lapply(created_shapes, function(x){
x
})) |>
terra::vect() |>
terra::buffer(buffer_edge) |>
terra::ext()
}
mosaiccr <- terra::crop(mosaic, poly_ext)
} else{
mosaiccr <- mosaic
}
} else{
if(inherits(shapefile, "list")){
created_shapes <- lapply(shapefile, function(x){
x
})
} else{
if(inherits(shapefile, "SpatVector")){
created_shapes <- sf::st_as_sf(shapefile) |> sf_to_polygon()
}
if(!"block" %in% colnames(shapefile)){
stop("`block` and `plot_id` must be in the column names of shapefile")
}
created_shapes <- split(shapefile, shapefile$block)
}
if(crop_to_shape_ext){
ress <- terra::res(mosaic)
if(sum(ress) != 2){
poly_ext <-
do.call(rbind, lapply(created_shapes, function(x){
x
})) |>
sf::st_transform(crs = sf::st_crs(terra::crs(mosaic))) |>
terra::vect() |>
terra::buffer(buffer_edge) |>
terra::ext()
} else{
poly_ext <-
do.call(rbind, lapply(created_shapes, function(x){
x
})) |>
terra::vect() |>
terra::buffer(buffer_edge) |>
terra::ext()
}
mosaiccr <- terra::crop(mosaic, poly_ext)
} else{
mosaiccr <- mosaic
}
}
segment_plot <- validate_and_replicate(segment_plot, created_shapes, verbose = verbose)
segment_individuals <- validate_and_replicate(segment_individuals, created_shapes, verbose = verbose)
threshold <- validate_and_replicate(threshold, created_shapes, verbose = verbose)
watershed <- validate_and_replicate(watershed, created_shapes, verbose = verbose)
segment_index <- validate_and_replicate(segment_index, created_shapes, verbose = verbose)
invert <- validate_and_replicate(invert, created_shapes, verbose = verbose)
includeopt <- validate_and_replicate(includeopt, created_shapes, verbose = verbose)
opening <- validate_and_replicate(opening, created_shapes, verbose = verbose)
closing <- validate_and_replicate(closing, created_shapes, verbose = verbose)
filter <- validate_and_replicate(filter, created_shapes, verbose = verbose)
erode <- validate_and_replicate(erode, created_shapes, verbose = verbose)
dilate <- validate_and_replicate(dilate, created_shapes, verbose = verbose)
grid <- validate_and_replicate(grid, created_shapes, verbose = verbose)
lower_noise <- validate_and_replicate(lower_noise, created_shapes, verbose = verbose)
if(!is.null(lower_size)){
lower_size <- validate_and_replicate(lower_size, created_shapes, verbose = verbose)
}
if(!is.null(upper_size)){
upper_size <- validate_and_replicate(upper_size, created_shapes, verbose = verbose)
}
if(!is.null(topn_lower)){
topn_lower <- validate_and_replicate(topn_lower, created_shapes, verbose = verbose)
}
if(!is.null(topn_upper)){
topn_upper <- validate_and_replicate(topn_upper, created_shapes, verbose = verbose)
}
#
if(is.null(indexes)){
if(verbose){
message("\014","\nComputing the indexes...\n")
}
if(nlyrs > 1 | !all(plot_index %in% names(mosaiccr))){
mind <- terra::rast(
Map(c,
lapply(seq_along(plot_index), function(i){
mosaic_index(mosaiccr,
index = plot_index[[i]],
r = r,
g = g,
b = b,
re = re,
nir = nir,
swir = swir,
tir = tir,
plot = FALSE)
})
)
)
} else{
plot_index <- names(mosaiccr)
mind <- mosaiccr
}
} else{
mind <- indexes
if(!all(segment_index %in% names(mind))){
stop("`segment_index` must be present in `indexes`")
}
}
results <- list()
result_indiv <- list()
extends <- terra::ext(mosaiccr)
usepickmask <- segment_pick & (segment_individuals[[1]] | segment_plot[[1]])
if(usepickmask){
if(build_shapefile & is.null(shapefile)){
mapview::mapview() |> mapedit::editMap()
}
mask <- suppressWarnings(
mosaic_segment_pick(mosaic,
basemap = basemap,
r = r,
g = g,
b = b,
max_pixels = max_pixels,
return = "mask")
)
}
ihaveamask <- !is.null(mask) & (segment_individuals[[1]] | segment_plot[[1]])
if(ihaveamask){
mask <- mask
}
for(j in seq_along(created_shapes)){
if(segment_plot[j] & segment_individuals[j]){
stop("Only `segment_plot` OR `segment_individuals` can be used", call. = FALSE)
}
if(verbose){
message("\014","\nExtracting data from block ", j, "\n")
}
if(inherits(created_shapes[[j]]$geometry, "sfc_POLYGON") & nrow(sf::st_coordinates(created_shapes[[j]]$geometry[[1]])) == 5 & grid[[j]]){
plot_grid <- created_shapes[[j]]
sf::st_geometry(plot_grid) <- "geometry"
if(crop_to_shape_ext){
ress <- terra::res(mosaic)
if(sum(ress) != 2){
plot_grid <-
plot_grid |>
sf::st_transform(crs = sf::st_crs(terra::crs(mosaic)))
}
ext_anal <-
plot_grid |>
terra::vect() |>
terra::buffer(buffer_edge) |>
terra::ext()
mind_temp <- terra::crop(mind, terra::ext(ext_anal))
if(!is.null(mask)){
mask <- terra::crop(mask, terra::ext(ext_anal))
}
} else{
mind_temp <- mind
}
extends <- terra::ext(mind_temp)
if(segment_plot[j]){
if(usepickmask | ihaveamask){
if(crop_to_shape_ext){
mask <- terra::crop(mask, terra::ext(ext_anal))
}
} else{
if(!segment_index[j] %in% names(mind_temp)){
stop("`segment_index` must be one of used in `plot_index`.")
}
thresh <- ifelse(threshold[j] == "Otsu", otsu(na.omit(terra::values(mind_temp)[, segment_index[j]])), threshold[j])
if(invert[j]){
mask <- mind_temp[[segment_index[j]]] > thresh
} else{
mask <- mind_temp[[segment_index[j]]] < thresh
}
}
mind_temp <- terra::mask(mind_temp, mask, maskvalues = TRUE)
# compute plot coverage
tmp <- exactextractr::exact_extract(mind_temp,
plot_grid,
coverage_area = TRUE,
force_df = TRUE,
progress = FALSE)
covered_area <-
purrr::map_dfr(tmp, function(x){
data.frame(covered_area = sum(na.omit(x)[, "coverage_area"]),
plot_area = sum(x[, "coverage_area"]))
}) |>
dplyr::mutate(coverage = covered_area / plot_area)
plot_grid <- dplyr::bind_cols(plot_grid, covered_area)
if(simplify){
plot_grid <- plot_grid |> sf::st_simplify(preserveTopology = TRUE)
}
rm(tmp)
}
# check if segmentation is performed (analyze individuals)
if(segment_individuals[j]){
if(usepickmask | ihaveamask){
if(crop_to_shape_ext){
mask <- terra::crop(mask, terra::ext(ext_anal))
}
} else{
thresh <- ifelse(threshold[j] == "Otsu", otsu(na.omit(terra::values(mind_temp)[, segment_index[j]])), threshold[j])
if(invert[j]){
mask <- mind_temp[[segment_index[j]]] < thresh
} else{
mask <- mind_temp[[segment_index[j]]] > thresh
}
}
dmask <- EBImage::Image(matrix(mask, ncol = nrow(mind_temp), nrow = ncol(mind_temp)))
dmask[is.na(dmask) == TRUE] <- 1
if(!isFALSE(filter[j]) & filter[j] > 1){
dmask <- EBImage::medianFilter(dmask, filter[j])
}
if(is.numeric(erode[j]) & erode[j] > 0){
dmask <- image_erode(dmask, size = erode[j])
}
if(is.numeric(dilate[j]) & dilate[j] > 0){
dmask <- image_dilate(dmask, size = dilate[j])
}
if(is.numeric(opening[j]) & opening[j] > 0){
dmask <- image_opening(dmask, size = opening[j])
}
if(is.numeric(closing[j]) & closing[j] > 0){
dmask <- image_closing(dmask, size = closing[j])
}
if(watershed[j]){
dmask <- EBImage::watershed(EBImage::distmap(dmask), tolerance = tolerance, ext = extension)
} else{
dmask <- EBImage::bwlabel(dmask)
}
resx <- terra::res(mosaiccr)[1]
resy <- terra::res(mosaiccr)[1]
conts <- EBImage::ocontour(matrix(dmask, ncol = nrow(mind_temp), nrow = ncol(mind_temp)))
conts <- conts[sapply(conts, nrow) > 2]
sf_df <- sf::st_sf(
geometry = lapply(conts, function(x) {
tmp <- x
tmp[, 2] <- extends[3] + (nrow(mask) - tmp[, 2]) * resy
tmp[, 1] <- extends[1] + tmp[, 1] * resy
geometry = sf::st_polygon(list(as.matrix(tmp |> poly_close())))
}),
data = data.frame(individual = paste0(1:length(conts))),
crs = terra::crs(mosaic)
)
if(simplify){
sf_df <- sf_df |> sf::st_simplify(preserveTopology = TRUE)
}
centroids <- suppressWarnings(sf::st_centroid(sf_df))
intersects <-
switch (includeopt[j],
"intersect" = sf::st_intersects(sf_df, plot_grid),
"centroid" = sf::st_within(centroids, plot_grid),
"covered" = sf::st_covered_by(sf_df, plot_grid),
"overlap" = sf::st_overlaps(sf_df, plot_grid),
)
plot_gridtmp <-
plot_grid |>
dplyr::mutate(plot_id_seq = paste0("P", leading_zeros(1:nrow(plot_grid), 4)))
plot_id <- data.frame(plot_id_seq = paste0(intersects))
valid_rows <- plot_id$plot_id_seq != "integer(0)"
sf_df <- sf_df[valid_rows, ]
plot_id <- paste0("P", leading_zeros(as.numeric(plot_id[valid_rows, ]), n = 4))
gridindiv <-
do.call(rbind,
lapply(1:nrow(sf_df), function(i){
compute_measures_mosaic(as.matrix(sf_df$geometry[[i]]))
})) |>
dplyr::mutate(plot_id_seq = plot_id,
individual = paste0(1:nrow(sf_df)),
geometry = sf_df$geometry) |>
dplyr::left_join(plot_gridtmp |> sf::st_drop_geometry(), by = dplyr::join_by(plot_id_seq)) |>
dplyr::select(-plot_id_seq) |>
dplyr::relocate(block, plot_id, individual, .before = 1) |>
sf::st_sf()
# control noise removing
if(!is.null(lower_size[j]) & !is.null(topn_lower[j]) | !is.null(upper_size[j]) & !is.null(topn_upper[j])){
stop("Only one of 'lower_*' or 'topn_*' can be used.")
}
ifelse(!is.null(lower_size[j]),
gridindiv <- gridindiv[gridindiv$area > lower_size[j], ],
gridindiv <- gridindiv[gridindiv$area > mean(gridindiv$area) * lower_noise[j], ])
if(!is.null(upper_size[j])){
gridindiv <- gridindiv[gridindiv$area < upper_size[j], ]
}
if(!is.null(topn_lower[j])){
gridindiv <- gridindiv[order(gridindiv$area),][1:topn_lower[j],]
}
if(!is.null(topn_upper[j])){
gridindiv <- gridindiv[order(gridindiv$area, decreasing = TRUE),][1:topn_upper[j],]
}
valindiv <-
exactextractr::exact_extract(x = mind_temp,
y = sf::st_sf(gridindiv),
fun = summarize_fun,
quantiles = summarize_quantiles,
progress = FALSE,
force_df = TRUE,
summarize_df = ifelse(is.function(summarize_fun), TRUE, FALSE))
if(inherits(valindiv, "list")){
if(is.null(summarize_fun)){
valindiv <- dplyr::bind_rows(valindiv, .id = "individual")
if("coverage_fraction" %in% colnames(valindiv)){
valindiv$coverage_fraction <- NULL
}
if("value" %in% colnames(valindiv)){
colnames(valindiv)[2] <- plot_index
}
valindiv <- valindiv |> dplyr::nest_by(individual)
} else{
valindiv <-
do.call(rbind, lapply(1:length(valindiv), function(i){
tmp <- transform(valindiv[[i]],
individual = paste0(i))
tmp[, c(ncol(tmp), ncol(tmp) - 1, 1:(ncol(tmp) - 2))]
}
))
if(length(plot_index) == 1){
colnames(valindiv) <- paste0(colnames(valindiv), ".", plot_index)
} else{
# colnames(valindiv) <- c("block", "plot_id", plot_index)
colnames(vals) <- paste0(colnames(vals), ".", plot_index)
}
}
} else{
if(length(plot_index) == 1){
colnames(valindiv) <- paste0(colnames(valindiv), ".", plot_index)
}
}
if(!is.null(summarize_fun)){
valindiv <-
dplyr::bind_cols(gridindiv, valindiv) |>
dplyr::mutate(individual = paste0(1:nrow(gridindiv)), .before = area) |>
sf::st_sf()
result_indiv[[j]] <- valindiv[order(valindiv$plot_id), ]
} else{
valindiv <- dplyr::bind_cols(dplyr::left_join(gridindiv, valindiv, by = dplyr::join_by(individual))) |> sf::st_sf()
result_indiv[[j]] <- valindiv[order(valindiv$plot_id), ]
}
} else{
dmask <- NULL
result_indiv[[j]] <- NULL
}
# extract the values for the individual plots
# check if a mask is used and no segmentation
if(!is.null(mask) & (!segment_individuals[[1]] & !segment_plot[[1]])){
mind_temp <- terra::mask(mind_temp, mask, maskvalues = TRUE)
}
vals <-
exactextractr::exact_extract(x = mind_temp,
y = plot_grid,
fun = summarize_fun,
quantiles = summarize_quantiles,
progress = FALSE,
force_df = TRUE,
summarize_df = ifelse(is.function(summarize_fun), TRUE, FALSE))
} else{
####### ANY TYPE OF POLYGON ########
# check if segmentation is performed
plot_grid <- created_shapes[[j]]
sf::st_geometry(plot_grid) <- "geometry"
if(crop_to_shape_ext){
ext_anal <-
plot_grid |>
terra::vect() |>
terra::buffer(buffer_edge) |>
terra::ext()
mind_temp <- terra::crop(mind, terra::ext(ext_anal))
if(!is.null(mask)){
mask <- terra::crop(mask, terra::ext(ext_anal))
}
} else{
mind_temp <- mind
}
extends <- terra::ext(mind_temp)
if(segment_plot[j]){
if(usepickmask | ihaveamask){
if(crop_to_shape_ext){
mask <- terra::crop(mask, terra::ext(ext_anal))
}
} else{
if(!segment_index[j] %in% names(mind_temp)){
stop("`segment_index` must be one of used in `plot_index`.")
}
thresh <- ifelse(threshold[j] == "Otsu", otsu(na.omit(terra::values(mind_temp)[, segment_index[j]])), threshold[j])
if(invert[j]){
mask <- mind_temp[[segment_index[j]]] > thresh
} else{
mask <- mind_temp[[segment_index[j]]] < thresh
}
}
# compute plot coverage
mind_temp <- terra::mask(mind_temp, mask, maskvalues = TRUE)
tmp <- exactextractr::exact_extract(mind_temp,
plot_grid,
coverage_area = TRUE,
force_df = TRUE,
progress = FALSE)
covered_area <-
purrr::map_dfr(tmp, function(x){
data.frame(covered_area = sum(na.omit(x)[, "coverage_area"]),
plot_area = sum(x[, "coverage_area"]))
}) |>
dplyr::mutate(coverage = covered_area / plot_area)
plot_grid <- dplyr::bind_cols(plot_grid, covered_area)
if(simplify){
plot_grid <- plot_grid |> sf::st_simplify(preserveTopology = TRUE)
}
rm(tmp)
}
if(segment_individuals[j]){
if(usepickmask | ihaveamask){
if(crop_to_shape_ext){
mask <- terra::crop(mask, terra::ext(ext_anal))
}
} else{
thresh <- ifelse(threshold[j] == "Otsu", otsu(na.omit(terra::values(mind_temp)[, segment_index[j]])), threshold[j])
if(invert[j]){
mask <- mind_temp[[segment_index[j]]] < thresh
} else{
mask <- mind_temp[[segment_index[j]]] > thresh
}
}
dmask <- EBImage::Image(matrix(matrix(mask), ncol = nrow(mind_temp), nrow = ncol(mind_temp)))
extends <- terra::ext(mind_temp)
dmask[is.na(dmask) == TRUE] <- 1
if(!isFALSE(filter[j]) & filter[j] > 1){
dmask <- EBImage::medianFilter(dmask, filter[j])
}
if(is.numeric(erode[j]) & erode[j] > 0){
dmask <- image_erode(dmask, size = erode[j])
}
if(is.numeric(dilate[j]) & dilate[j] > 0){
dmask <- image_dilate(dmask, size = dilate[j])
}
if(is.numeric(opening[j]) & opening[j] > 0){
dmask <- image_opening(dmask, size = opening[j])
}
if(is.numeric(closing[j]) & closing[j] > 0){
dmask <- image_closing(dmask, size = closing[j])
}
if(watershed[j]){
dmask <- EBImage::watershed(EBImage::distmap(dmask), tolerance = tolerance, ext = extension)
} else{
dmask <- EBImage::bwlabel(dmask)
}
conts <- EBImage::ocontour(dmask)
conts <- conts[sapply(conts, nrow) > 2]
resx <- terra::res(mosaiccr)[1]
resy <- terra::res(mosaiccr)[1]
sf_df <- sf::st_sf(
geometry = lapply(conts, function(x) {
tmp <- x
tmp[, 2] <- extends[3] + (nrow(mask) - tmp[, 2]) * resy
tmp[, 1] <- extends[1] + tmp[, 1] * resy
geometry = sf::st_polygon(list(as.matrix(tmp |> poly_close())))
}),
data = data.frame(individual = paste0(1:length(conts))),
crs = terra::crs(mosaic)