-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils_polygon.R
1365 lines (1282 loc) · 40.7 KB
/
utils_polygon.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
#' Utilities for Polygons
#'
#' @description
#' Several useful functions for analyzing polygons. All of them are based on a
#' set of coordinate points that describe the edge of the object(s). If a list
#' of polygons is provided, it loops through the list and computes what is
#' needed for each element of the list.
#'
#'* Polygon measures
#'
#' - `conv_hull()` Computes the convex hull of a set of points.
#'
#' - `conv_hull_unified()` Computes the convex hull of a set of points. Compared
#' to `conv_hull()`, `conv_hull_unified()` binds (unifies) the coordinates when
#' x is a list of coordinates.
#'
#' - `poly_area()` Computes the area of a polygon given by the vertices in the
#' vectors x and y using the Shoelace formula, as follows (Lee and Lim,
#' 2017): \deqn{A=\frac{1}{2}\left|\sum_{i=1}^{n}\left(x_{i} y_{i+1}-x_{i+1}
#' y_{i}\right)\right|} where `x` and `y` are the coordinates that form the
#' corners of a polygon, and `n` is the number of coordinates.
#'
#' - `poly_angles()` Calculates the internal angles of the polygon using the
#' law of cosines.
#'
#'
#' - `poly_lw()` Returns the length and width of a polygon based on its
#' alignment to the y-axis (with poly_align()). The length is defined as the
#' range along the x-axis, and the width is defined as the range on the y-axis.
#'
#' - `poly_mass()` Computes the center of mass (centroid) of a polygon given by
#' the vertices in the vectors x and y using the following formulas:
#'
#' \deqn{C_x = \frac{1}{6A} \sum_{i=1}^{n} (x_i + x_{i+1}) (x_i y_{i+1} - x_{i+1} y_i)}
#' \deqn{C_y = \frac{1}{6A} \sum_{i=1}^{n} (y_i + y_{i+1}) (x_i y_{i+1} - x_{i+1} y_i)} where `C_x` and `C_y` are the coordinates of the center of mass, `A` is the
#' area of the polygon computed by the Shoelace formula, `x` and `y` are the
#' coordinates that form the corners of the polygon, and `n` is the number of
#' coordinates.
#'
#' - `poly_solidity()` Computes the solidity of a shape as the ratio of
#' the shape area and the convex hull area.
#'
#' * Perimeter measures
#' - `poly_slide()` Slides the coordinates of a polygon given by the vertices
#' in the vectors x and y so that the id-th point becomes the first one.
#'
#' - `poly_distpts()` Computes the Euclidean distance between every point
#' of a polygon given by the vertices in the vectors x and y.
#'
#' - `poly_centdist()` Computes the Euclidean distance between every point on
#' the perimeter and the centroid of the object.
#'
#' - `poly_centdist_mass()` Computes the Euclidean distance between every point on
#' the perimeter and the center of mass of the object.
#'
#' - `poly_perimeter()` Computes the perimeter of a polygon given by the
#' vertices in the vectors x and y.
#'
#' - `poly_caliper()` Computes the caliper (also called the Feret's diameter)
#' of a polygon given by the vertices in the vectors x and y.
#'
#'
#' * Circularity measures (Montero et al. 2009).
#'
#' - `poly_circularity()` computes the circularity (C), also called shape
#' compactness or roundness measure, of an object. It is given by `C = P^2 / A`,
#' where P is the perimeter and A is the area of the object.
#'
#' - `poly_circularity_norm()` computes the normalized circularity (Cn), which
#' is unity for a circle. This measure is invariant under translation,
#' rotation, scaling transformations, and is dimensionless. It is given by:
#' `Cn = P^2 / 4*pi*A`.
#'
#' - `poly_circularity_haralick()` computes Haralick's circularity (CH). The
#' method is based on computing all Euclidean distances from the object
#' centroid to each boundary pixel. With this set of distances, the mean (`m`)
#' and the standard deviation (`sd`) are computed. These statistical parameters
#' are used to calculate the circularity, CH, of a shape as `CH = m/sd`.
#'
#' - `poly_convexity()` computes the convexity of a shape using the ratio
#' between the perimeter of the convex hull and the perimeter of the polygon.
#'
#' - `poly_eccentricity()` computes the eccentricity of a shape using the
#' ratio of the eigenvalues (inertia axes of coordinates).
#'
#' - `poly_elongation()` computes the elongation of a shape as `1 - width / length`.
#'
#'
#' * Utilities for polygons
#'
#' - `poly_check()` Checks a set of coordinate points and returns a matrix
#' with x and y columns.
#'
#' - `poly_is_closed()` Returns a logical value indicating if a polygon is
#' closed.
#'
#' - `poly_close()` and `poly_unclose()` close and unclose a polygon,
#' respectively.
#'
#' - `poly_rotate() `Rotates the polygon coordinates by an angle (0-360
#' degrees) in the counterclockwise direction.
#'
#' - `poly_flip_x()`, `poly_flip_y()` flip shapes along the x-axis and y-axis,
#' respectively.
#'
#' - `poly_align()` Aligns the coordinates along their longer axis using the
#' var-cov matrix and eigen values.
#'
#' - `poly_center()` Centers the coordinates on the origin.
#'
#' - `poly_sample()` Samples n coordinates from existing points. Defaults
#' to 50.
#'
#' - `poly_sample_prop()` Samples a proportion of coordinates from existing
#' points. Defaults to 0.1.
#'
#' - `poly_spline()` Interpolates the polygon contour.
#'
#' - `poly_smooth()` Smooths the polygon contour using a simple moving average.
#'
#' - `poly_jitter()` Adds a small amount of noise to a set of point
#' coordinates. See [base::jitter()] for more details.
#'
#'
#' * `poly_measures()` Is a wrapper around the `poly_*()` functions.
#'
#' @param x A 2-column matrix with the `x` and `y` coordinates. If `x` is a list
#' of vector coordinates, the function will be applied to each element using
#' [base::lapply()] or [base::sapply()].
#' @param fp The ID of the point that will become the new first point. Defaults
#' to 1.
#' @param angle The angle (0-360) to rotate the object.
#' @param plot Should the object be plotted? Defaults to `TRUE`.
#' @param noise_x,noise_y A numeric factor to define the noise added to the `x`
#' and `y` axes, respectively. See [base::jitter()] for more details.
#' @param vertices The number of spline vertices to create.
#' @param k The number of points to wrap around the ends to obtain a smooth
#' periodic spline.
#' @param n,prop The number and proportion of coordinates to sample from the
#' perimeter coordinates. In` poly_smooth()`, these arguments can be used to
#' sample points from the object's perimeter before smoothing.
#' @param niter An integer indicating the number of smoothing iterations.
#'
#' @name utils_polygon
#' @return
#' * `conv_hull()` and `poly_spline()` returns a matrix with `x` and `y`
#' coordinates for the convex hull/smooth line in clockwise order. If `x` is a
#' list, a list of points is returned.
#'
#' * `poly_area()` returns a `double`, or a numeric vector if `x` is a list of
#' vector points.
#'
#' * `poly_mass()` returns a `data.frame` containing the coordinates for the
#' center of mass, as well as for the maximum and minimum distance from contour
#' to the center of mass.
#'
#' * `poly_slides()`, `poly_distpts()`, `poly_spline()`, `poly_close()`,
#' `poly_unclose()`, `poly_rotate()`, `poly_jitter()`, `poly_sample()`,
#' `poly_sample_prop()`, and `poly_measures` returns a `data.frame`.
#'
#' * `poly_perimeter()`, `poly_lw()`, `poly_eccentricity()`,
#' `poly_convexity()`, `poly_caliper()`, `poly_elongation()`,
#' `poly_circularity_norm()`, `poly_circularity_haralick()` returns a `double`.
#'
#'
#' @importFrom grDevices chull
#' @importFrom stats spline
#' @export
#' @references
#' Lee, Y., & Lim, W. (2017). Shoelace Formula: Connecting the Area of a
#' Polygon and the Vector Cross Product. The Mathematics Teacher, 110(8),
#' 631–636. \doi{10.5951/mathteacher.110.8.0631}
#'
#' Montero, R. S., Bribiesca, E., Santiago, R., & Bribiesca, E. (2009). State
#' of the Art of Compactness and Circularity Measures. International
#' Mathematical Forum, 4(27), 1305–1335.
#'
#' Chen, C.H., and P.S.P. Wang. 2005. Handbook of Pattern Recognition and
#' Computer Vision. 3rd ed. World Scientific.
#'
#' @examples
#' if (interactive() && requireNamespace("EBImage")) {
#' library(pliman)
#' # A 2 x 2 square
#' df <- draw_square(side = 2)
#'
#' # square area
#' poly_area(df)
#'
#' # polygon perimeter
#' poly_perimeter(df)
#'
#'# center of mass of the square
#' cm <- poly_mass(df)
#' plot_mass(cm)
#'
#'# The convex hull will be the vertices of the square
#' (conv_square <- conv_hull(df) |> poly_close())
#' plot_contour(conv_square,
#' col = "blue",
#' lwd = 6)
#' poly_area(conv_square)
#'
#'
#'################### Example with a polygon ##################
#' x <- c(0, 1, 2, 3, 5, 2, -1, 0, 0)
#' y <- c(5, 6.5, 7, 3, 1, 1, 0, 2, 5)
#' df_poly <- cbind(x, y)
#'
#' # area of the polygon
#' plot_polygon(df_poly, fill = "red")
#' poly_area(df_poly)
#'
#' # perimeter of the polygon
#' poly_perimeter(df_poly)
#'
#'# center of mass of polygon
#' cm <- poly_mass(df_poly)
#' plot_mass(cm, col = "blue")
#'
#'# vertices of the convex hull
#' (conv_poly <- conv_hull(df_poly))
#'
#'# area of the convex hull
#' poly_area(conv_poly)
#'
#' plot_polygon(conv_poly,
#' fill = "red",
#' alpha = 0.2,
#' add = TRUE)
#'
#'
#' ############ example of circularity measures ################
#' tri <- draw_circle(n = 200, plot = FALSE)
#' plot_polygon(tri, aspect_ratio = 1)
#' poly_circularity_norm(tri)
#'
#' set.seed(1)
#' tri2 <-
#' draw_circle(n = 200, plot = FALSE) |>
#' poly_jitter(noise_x = 100, noise_y = 100, plot = FALSE)
#'
#' plot_polygon(tri2, aspect_ratio = 1)
#' poly_circularity_norm(tri2)
#' }
## check a coordinate set of points
poly_check <- function(x) {
if (inherits(x, "list")) {
lapply(x, poly_check)
} else{
if (is.data.frame(x)) {
x <- as.matrix(x)
}
return(x)
}
}
#' @name utils_polygon
#' @export
# check if a polygon is closed
poly_is_closed <- function(x) {
if (inherits(x, "list")) {
sapply(x, poly_is_closed)
} else {
coord <- poly_check(x)
return(identical(coord[1, ], coord[nrow(coord), ]))
}
}
#' @name utils_polygon
#' @export
# close a polygon, if unclosed
poly_close <- function(x) {
if (inherits(x, "list")) {
lapply(x, poly_close)
} else {
coord <- poly_check(x)
ifelse(poly_is_closed(coord),
return(coord),
return(rbind(coord, coord[1, ])))
}
}
#' @name utils_polygon
#' @export
# unclose a polygon, if closed
poly_unclose <- function(x) {
if (inherits(x, "list")) {
lapply(x, poly_unclose)
} else {
coord <- poly_check(x)
ifelse(poly_is_closed(coord),
return(coord[-nrow(coord), ]),
return(coord))
}
}
#' @name utils_polygon
#' @export
# compute the internal angles of a polygon
poly_angles <- function(x) {
if (inherits(x, "list")) {
lapply(x, function(x){
help_poly_angles(poly_unclose(x))
})
} else {
coord <- poly_unclose(x)
help_poly_angles(coord)
}
}
#' @name utils_polygon
#' @export
poly_limits <- function(x) {
if (inherits(x, "list")) {
res <- do.call(rbind, lapply(x, help_limits))
colnames(res) <- c("xmin", "xmax", "ymin", "ymax")
return(res)
} else {
res <- t(as.data.frame(help_limits(x)))
colnames(res) <- c("xmin", "xmax", "ymin", "ymax")
rownames(res) <- NULL
return(res)
}
}
#' @name utils_polygon
#' @export
# computes the convex hull
conv_hull <- function(x){
if (inherits(x, "list")) {
lapply(x, conv_hull)
} else{
vcts <- poly_check(x)
vec <- chull(vcts)
return(vcts[vec, ])
}
}
#' @name utils_polygon
#' @export
conv_hull_unified <- function(x){
if(inherits(x, "list")){
unified <- do.call(rbind, lapply(x, function(x){x}))
} else{
unified <- x
}
ch <- unified[chull(unified), ]
ch <- rbind(ch, ch[1, ])
return(ch)
}
#' @name utils_polygon
#' @export
# Compute the area of a polygon using shoelace formula
# adapted from https://www.geeksforgeeks.org/area-of-a-polygon-with-given-n-ordered-vertices/
poly_area <- function(x){
help_area(x)
}
#' @name utils_polygon
#' @export
# Slides the coordinates so that the id-th point become the first one.
poly_slide <- function(x, fp = 1){
if (inherits(x, "list")) {
sapply(x, help_slide, fp)
} else{
help_slide(x, fp = fp)
}
}
#' @name utils_polygon
#' @export
# calculates the euclidean distance between every points of a shape
poly_distpts <- function(x) {
if (inherits(x, "list")) {
lapply(x, help_distpts)
} else{
help_distpts(x)
}
}
#' @name utils_polygon
#' @export
# Computes the euclidean distance between every points and the centroid
poly_centdist <- function(x) {
if (inherits(x, "list")) {
lapply(x, help_centdist)
} else{
help_centdist(x)
}
}
#' @name utils_polygon
#' @export
# Computes the euclidean distance between every points and the centroid
poly_centdist_mass <- function(x) {
if (inherits(x, "list")) {
lapply(x, help_centdist2)
} else{
help_centdist2(x)
}
}
#' @name utils_polygon
#' @export
# calculates the perimeter
poly_perimeter <- function(x) {
if (inherits(x, "list")) {
sapply(x, function(x){sum(help_distpts(x))})
} else{
return(sum(help_distpts(x)))
}
}
#' @name utils_polygon
#' @export
# rotate
poly_rotate <- function(x, angle, plot = TRUE) {
if (inherits(x, "list")) {
rotated <- lapply(x, help_rotate, angle)
if(isTRUE(plot)){
plot_polygon(rotated)
}
return(rotated)
} else{
rotated <- help_rotate(x, angle)
if(isTRUE(plot)){
plot_polygon(rotated)
}
return(rotated)
}
}
#' @name utils_polygon
#' @export
poly_align <- function(x, plot = TRUE) {
if (inherits(x, "list")) {
aligned <- lapply(x, help_align)
if(isTRUE(plot)){
plot_polygon(aligned, merge = FALSE, aspect_ratio = 1)
}
return(aligned)
} else{
aligned <- help_align(x)
if(isTRUE(plot)){
plot_polygon(aligned, merge = FALSE, aspect_ratio = 1)
}
return(aligned)
}
}
#' @name utils_polygon
#' @export
poly_center <- function(x, plot = TRUE) {
if (inherits(x, "list")) {
centered <- lapply(x, poly_center)
if(isTRUE(plot)){
plot_polygon(centered, merge = FALSE, aspect_ratio = 1)
}
return(centered)
} else{
centered <-
data.frame(X1 = x[,1] - mean(x[,1]),
X2 = x[,2] - mean(x[,2]))
if(isTRUE(plot)){
plot_polygon(centered, merge = FALSE, aspect_ratio = 1)
}
return(centered)
}
}
#' @name utils_polygon
#' @export
# computes width and length
poly_lw <- function(x) {
lw <- help_lw(x)
colnames(lw) <- c("length", "width")
return(lw)
}
#' @name utils_polygon
#' @export
poly_eccentricity <- function(x) {
help_eigen_ratio(x)
}
#' @name utils_polygon
#' @export
# computes the convexity
poly_convexity <- function(x) {
if (inherits(x, "list")) {
sapply(x, function(x){sum(help_distpts(x[chull(x), ])) / sum(help_distpts(x))})
} else{
return(sum(help_distpts(x[chull(x), ])) / sum(help_distpts(x)))
}
}
#' @name utils_polygon
#' @export
poly_caliper <- function(x) {
if (inherits(x, "list")){
sapply(x, poly_caliper)
} else{
if(nrow(x) > 250){
x <- landmarks_regradi(x, n = 250, plot = FALSE)$coord
}
return(max(dist(x)))
}
}
#' @name utils_polygon
#' @export
# computes the elongation
poly_elongation <- function(x) {
help_elongation(x)
}
#' @name utils_polygon
#' @export
# computes the solidity
poly_solidity <- function(x) {
if (inherits(x, "list")) {
sapply(x, function(x){
help_area(x) / help_area(x[chull(x), ])
})
} else{
help_area(x) / help_area(x[chull(x), ])
}
}
#' @name utils_polygon
#' @export
# flips shapes in along the y axis
poly_flip_y <- function(x) {
if (inherits(x, "list")) {
lapply(x, help_flip_y)
} else{
help_flip_y(x)
}
}
#' @name utils_polygon
#' @export
# flips shapes in along the x axis
poly_flip_x <- function(x) {
if (inherits(x, "list")) {
lapply(x, help_flip_x)
} else{
help_flip_x(x)
}
}
#' @name utils_polygon
#' @export
# sample n points
poly_sample <- function(x, n = 50) {
if (inherits(x, "list")) {
lapply(x, poly_sample, n)
} else{
coord <- poly_check(x)
if (nrow(coord) < n){
stop("Less coordinates than n", call. = FALSE)
}
sampled <- round(seq(1, nrow(coord), len = n + 1)[-(n + 1)])
return(coord[sampled, ])
}
}
#' @name utils_polygon
#' @export
# sample a proportion of points
poly_sample_prop <- function(x, prop = 0.1) {
if (inherits(x, "list")) {
lapply(x, poly_sample_prop, prop)
} else{
coord <- poly_check(x)
return(poly_sample(coord, n = nrow(coord) * prop))
}
}
#' @name utils_polygon
#' @export
# add an small amount of noise in a set of coordinates
poly_jitter <- function(x,
noise_x = 1,
noise_y = 1,
plot = TRUE) {
if (inherits(x, "list")) {
lapply(x, poly_jitter, noise_x, noise_y, plot)
} else{
coord <- poly_check(x)
coord[,1] <- jitter(coord[,1], factor = noise_x)
coord[,2] <- jitter(coord[,2], factor = noise_y)
if(isTRUE(plot)){
plot_polygon(coord)
}
return(coord)
}
}
#' @name utils_polygon
#' @export
# calculates the 'circularity measure'. Also called 'compactness' and 'shape factor'
poly_circularity <- function(x) {
if (inherits(x, "list")) {
sapply(x, function(x){
sum(help_distpts(x))^2 / help_area(x)
})
} else{
sum(help_distpts(x))^2 / help_area(x)
}
}
#' @name utils_polygon
#' @export
# calculates calculates Haralick's circularity
poly_circularity_norm <- function(x) {
if (inherits(x, "list")) {
sapply(x, function(x){
(help_area(x) * 4 * pi) / sum(help_distpts(x))^2
})
} else{
(help_area(x) * 4 * pi) / sum(help_distpts(x))^2
}
}
#' @name utils_polygon
#' @export
# calculates calculates Haralick's circularity
poly_circularity_haralick <- function(x) {
if (inherits(x, "list")) {
sapply(x, function(x){
cd <- help_centdist(x)
mean(cd) / sd(cd)
})
} else{
cd <- help_centdist(x)
mean(cd) / sd(cd)
}
}
#' @name utils_polygon
#' @export
poly_mass <- function(x){
if (inherits(x, "list") | inherits(x, "iefourier_lst")) {
cm <-
do.call(rbind,
lapply(x, function(x){
cm <- t(help_mc(x))
})
)
colnames(cm) <- c("x", "y")
return(cm)
} else{
cm <- t(help_mc(x))
colnames(cm) <- c("x", "y")
return(cm)
}
}
#' @name utils_polygon
#' @export
poly_spline <- function(x,
vertices = 100,
k = 2){
# adapted from https://gis.stackexchange.com/questions/24827/smoothing-polygons-in-contour-map
if (inherits(x, "list")) {
lapply(x, poly_spline, vertices, k)
} else{
if(is.data.frame(x) | is.matrix(x)){
xy <- x
}
n <- dim(xy)[1]
if (k >= 1) {
data <- rbind(xy[(n-k+1):n,], xy, xy[1:k, ])
} else {
data <- xy
}
# Spline the x and y coordinates.
data.spline <- spline(1:(n+2*k), data[,1], n=vertices)
x <- data.spline$x
x1 <- data.spline$y
x2 <- spline(1:(n+2*k), data[,2], n=vertices)$y
sl <- cbind(x1, x2)[k < x & x <= n+k, ]
# ensure a closed line
rbind(sl, sl[1,])
}
}
#' @name utils_polygon
#' @export
poly_smooth <- function(x,
niter = 10,
n = NULL,
prop = NULL,
plot = TRUE) {
if (inherits(x, "list")) {
coords <- lapply(x, poly_smooth,niter, n, prop, plot)
if(isTRUE(plot)){
plot_polygon(coords, merge = FALSE, aspect_ratio = 1)
}
return(coords)
} else{
coords <- poly_check(x)
if(!is.null(n) ){
coords <-
poly_sample(coords,
n = n)
}
if(!is.null(prop) ){
coords <-
poly_sample_prop(coords,
prop = prop)
}
coords <- help_smoth(coords, niter)
if(isTRUE(plot)){
plot_polygon(coords, aspect_ratio = 1)
}
return(coords)
}
}
#' @name utils_polygon
#' @export
poly_measures <- function(x){
if (inherits(x, "list")) {
valid <- which(sapply(x, function(x){length(as.matrix(x))}) > 2)
coord <- x[valid]
res <- do.call(rbind, lapply(coord, poly_measures))
res$id <- 1:nrow(res)
shape <- res[, c(ncol(res), 1:ncol(res) -1) ]
return(shape)
} else{
coord <- poly_check(x)
mass <- poly_mass(coord)
ch <- coord[chull(coord), ]
area_ch <- help_area(ch)
lw <- help_lw(coord)
centdist <- help_centdist(coord)
radius_mean = mean(centdist)
radius_min = min(centdist)
radius_max = max(centdist)
radius_sd = sd(centdist)
area <- help_area(coord)
shape <- data.frame(x = mass[[1]],
y = mass[[2]],
area = area,
area_ch = area_ch,
perimeter = sum(help_distpts(coord)),
radius_mean = radius_mean,
radius_min = radius_min,
radius_max = radius_max,
radius_sd = radius_sd,
radius_ratio = radius_max / radius_min,
diam_mean = radius_mean * 2,
diam_min = radius_min * 2,
diam_max = radius_max * 2,
caliper = lw[1],
length = lw[1],
width = lw[2],
solidity = area / area_ch,
convexity = poly_convexity(coord),
elongation = poly_elongation(coord),
circularity = poly_circularity(coord),
circularity_haralick = poly_circularity_haralick(coord),
circularity_norm = poly_circularity_norm(coord),
eccentricity = poly_eccentricity(coord),
pcv = poly_pcv(coord))
}
return(shape)
}
#' Utilities for plotting polygons
#'
#' @description
#' - `plot_contour()` Plot contour lines.
#' - `plot_polygon()` Plots a polygon describing the objects.
#' - `plot_mass()` Plots the center of mass along with maximum and minimum
#' radius.
#' - `plot_ellipse()` Plots an ellipse that fits the major and minor axis for
#' each object.
#'
#' @param x A 2-column matrix with the `x` and `y` coordinates.
#' @param id The object identification (numeric) to plot the contour/ellipse. By
#' default (`id = NULL`), the contour is plotted to all objects.
#' @param col,lwd,cex The color, width of the lines, and size of point,
#' respectively.
#' @param fill,border,alpha The color to fill the polygon, the color of the
#' polygon's border, and the alpha transparency (1 opaque, 0 transparent).
#' @param random_fill Fill multiple objects with random colors? Defaults to
#' `TRUE`.
#' @param points Plot the points? Defaults to `FALSE`.
#' @param merge Merge multiple objects into a single plot? Defaults to `TRUE`.
#' If `FALSE`, a single call `plot()` will be used for each objects. Use
#' `nrow` and `ncol` to control the number of rows and columns of the window.
#' @param add Add the current plot to a previous one? Defaults to `FALSE`.
#' @param nrow,ncol The number of rows and columns to use in the composite
#' image. Defaults to `NULL`, i.e., a square grid is produced.
#' @param aspect_ratio The x/y aspect ratio. Defaults to `1`. This will set up
#' the window so that one data unit in the y direction is equal to one data
#' unit in the x direction. Set `aspect_ratio = NULL` to fit the object to the
#' window size.
#' @param show_id Shows the object id? Defaults to `TRUE`.
#' @param xlim,ylim A numeric vector of length 2 (min; max) indicating the range
#' of `x` and `y`-axes.
#' @param object An object computed with [analyze_objects()].
#' @param ...
#' * For `plot_contour()` and `plot_ellipse()` further arguments passed on to
#' [graphics::lines()].
#' * For `plot_mass()`, further arguments passed on to [graphics::points()].
#' * For `plot_polygon()`, further arguments passed on to
#' [graphics::polygon()].
#'
#' @return a `NULL` object.
#' @name utils_polygon_plot
#' @export
#'
#' @examples
#' plot_polygon(contours)
#' plot_contour(contours[[1]], id = 6, col = "red", lwd = 3)
plot_contour <- function(x,
id = NULL,
col = "black",
lwd = 1,
...){
if (inherits(x, "list") | inherits(x, "iefourier_lst")) {
if(is.null(id)){
invisible(lapply(x, plot_contour, id, col, lwd))
} else{
invisible(lapply(x[id], plot_contour, id, col, lwd))
}
} else{
coord <- poly_check(x)
lines(coord,
col = col,
xlab = "",
ylab = "",
lwd = lwd,
asp = 1)
}
}
#' @name utils_polygon_plot
#' @export
plot_polygon <- function(x,
fill = "gray",
random_fill = TRUE,
points = FALSE,
merge = TRUE,
border = "black",
alpha = 1,
add = FALSE,
nrow = NULL,
ncol = NULL,
aspect_ratio = 1,
show_id = TRUE,
xlim = NULL,
ylim = NULL,
...){
if (inherits(x, "list") | inherits(x, "iefourier_lst")) {
if(isTRUE(merge)){
if(inherits(x[[1]][[1]], "landmarks_regradi")){
x <- lapply(x, function(x){
x[[1]]$coords
})
}
binds <- do.call(rbind,
lapply(x, function(x){
x
}))
lims <- apply(binds, 2, range)
xlim <- c(lims[1], lims[2])
ylim <- c(lims[3], lims[4])
plot(binds,
axes = FALSE,
type = "n",
xlab = "",
ylab = "",
xlim = xlim,
ylim = ylim,
asp = 1)
axis(1)
axis(2)
ifelse(random_fill == TRUE,
colf <- random_color(n = length(x)),
colf <- rep(fill, length(x)))
if(isTRUE(show_id)){
mass <- poly_mass(x)
xx <- mass[,1]
xy <- mass[,2]
labs <- names(x)
}
for (i in seq_along(x)) {
plot_polygon(x[[i]],
add = TRUE,
fill = colf[[i]],
border = border,
alpha = alpha,
aspect_ratio = aspect_ratio,
...)
if(isTRUE(show_id)){
text(xx[i], xy[i], label = labs[i])
}
}
} else{
if(inherits(x[[1]][[1]], "landmarks_regradi")){
x <- lapply(x, function(x){
x[[1]]$coords
})
}
num_plots <- length(x)
if (is.null(nrow) && is.null(ncol)){
ncol <- ceiling(sqrt(num_plots))
nrow <- ceiling(num_plots/ncol)
}
if (is.null(ncol)){
ncol <- ceiling(num_plots/nrow)
}
if (is.null(nrow)){
nrow <- ceiling(num_plots/ncol)
}
op <- par(mfrow = c(nrow, ncol))
on.exit(par(op))
return(lapply(x, plot_polygon, fill, random_fill, points, merge, border, alpha, add, aspect_ratio = aspect_ratio, ...))
}
} else{
if(inherits(x, "landmarks_regradi")){
coords <- x$coords
} else{
coords <- poly_check(x)
}
if(isFALSE(add)){
plot(coords,
axes = FALSE,
type = "n",
xlab = "",
ylab = "",
xlim = xlim,
ylim = ylim,
asp = aspect_ratio)
axis(1)
axis(2)
}
if (!isFALSE(fill)) {
polygon(coords,
col = rgb(t(col2rgb(fill) / 255), alpha = alpha),
border = border,
...)
} else{
polygon(coords,
border = border,
...)
}
if(isTRUE(points)){
points(coords, pch = 16)
}
}
}
#' @name utils_polygon_plot
#' @export
plot_mass <- function(x,
id = NULL,
col = "black",
cex = 1,
lwd = 1){
if (inherits(x, "list")) {