-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils_objects.R
1202 lines (1116 loc) · 44.8 KB
/
utils_objects.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 working with image objects
#'
#' * `object_id()` get the object identification in an image.
#' * `object_coord()` get the object coordinates and (optionally) draw a
#' bounding rectangle around multiple objects in an image.
#' * `object_contour()` returns the coordinates (`x` and `y`) for the contours
#' of each object in the image.
#' * `object_isolate()` isolates an object from an image.
#' @name utils_objects
#'
#' @inheritParams analyze_objects
#' @param img An image of class `Image` or a list of `Image` objects.
#' @param center If `TRUE` returns the object contours centered on the origin.
#' @param id
#' * For `object_coord()`, a vector (or scalar) of object `id` to compute the
#' bounding rectangle. Object ids can be obtained with [object_id()]. Set `id =
#' "all"` to compute the coordinates for all objects in the image. If `id =
#' NULL` (default) a bounding rectangle is drawn including all the objects.
#' * For `object_isolate()`, a scalar that identifies the object to be extracted.
#'
#' @param dir_original The directory containing the original images. Defaults
#' to `NULL`, which means that the current working directory will be
#' considered.
#' @param index The index to produce a binary image used to compute bounding
#' rectangle coordinates. See [image_binary()] for more details.
#' @param invert Inverts the binary image, if desired. Defaults to `FALSE`.
#' @param opening,closing,filter **Morphological operations (brush size)**
#' * `opening` performs an erosion followed by a dilation. This helps to
#' remove small objects while preserving the shape and size of larger objects.
#' * `closing` performs a dilatation followed by an erosion. This helps to
#' fill small holes while preserving the shape and size of larger objects.
#' * `filter` performs median filtering in the binary image. Provide a positive
#' integer > 1 to indicate the size of the median filtering. Higher values are
#' more efficient to remove noise in the background but can dramatically impact
#' the perimeter of objects, mainly for irregular perimeters such as leaves
#' with serrated edges.
#'
#' Hierarchically, the operations are performed as opening > closing > filter.
#' The value declared in each argument will define the brush size.
#'@param smooth whether the object contours should be smoothed with
#' [poly_smooth()]. Defaults to `FALSE`. To smooth use a numeric value
#' indicating the number of interactions used to smooth the contours.
#' @param fill_hull Fill holes in the objects? Defaults to `FALSE`.
#' @param watershed If `TRUE` (default) performs watershed-based object
#' detection. This will detect objects even when they are touching one other.
#' 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 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 informed, this value will be used as a threshold.
#' Inform any non-numeric value different than "Otsu" to iteratively chosen
#' the threshold based on a raster plot showing pixel intensity of the index.
#' @param edge The number of pixels in the edge of the bounding rectangle.
#' Defaults to `2`.
#' @param extension,tolerance,object_size Controls the watershed segmentation of
#' objects in the image. See [analyze_objects()] for more details.
#' @param plot Shows the image with bounding rectangles? Defaults to
#' `TRUE`.
#' @param parallel Processes the images asynchronously (in parallel) in separate
#' R sessions running in the background on the same machine. It may speed up
#' the processing time when `image` is a list. The number of sections is set
#' up to 50% of available cores.
#' @param workers A positive numeric scalar or a function specifying the maximum
#' number of parallel processes that can be active at the same time.
#' @param ...
#' * For `object_isolate()`, further arguments passed on to [object_coord()].
#' * For `object_id()`, further arguments passed on to [analyze_objects()].
#' @return
#' * `object_id()` An image of class `"Image"` containing the object's
#' identification.
#' * `object_coord()` A list with the coordinates for the bounding rectangles.
#' If `id = "all"` or a numeric vector, a list with a vector of coordinates is
#' returned.
#' * `object_isolate()` An image of class `"Image"` containing the isolated
#' object.
#' @export
#' @examples
#' if (interactive() && requireNamespace("EBImage")) {
#' library(pliman)
#' img <- image_pliman("la_leaves.jpg")
#' # Get the object's (leaves) identification
#' object_id(img)
#'
#' # Get the coordinates and draw a bounding rectangle around leaves 1 and 3
#' object_coord(img, id = c(1, 3))
#'
#' # Isolate leaf 3
#' isolated <- object_isolate(img, id = 3)
#' plot(isolated)
#'
#' }
object_coord <- function(img,
id = NULL,
index = "NB",
watershed = TRUE,
invert = FALSE,
opening = FALSE,
closing = FALSE,
filter = FALSE,
fill_hull = FALSE,
threshold = "Otsu",
edge = 2,
extension = NULL,
tolerance = NULL,
object_size = "medium",
parallel = FALSE,
workers = NULL,
plot = TRUE){
if(inherits(img, "list")){
if(!all(sapply(img, class) == "Image")){
stop("All images must be of class 'Image'")
}
if(parallel == TRUE){
nworkers <- ifelse(is.null(workers), trunc(parallel::detectCores()*.5), workers)
future::plan(future::multisession, workers = nworkers)
on.exit(future::plan(future::sequential))
`%dofut%` <- doFuture::`%dofuture%`
message("Image processing using multiple sessions (",nworkers, "). Please wait.")
foreach::foreach(i = seq_along(img)) %dofut%{
object_coord(img[[i]], id, index, invert,
fill_hull, threshold, edge, extension, tolerance,
object_size, plot)
}
} else{
lapply(img, object_coord, id, index, invert, fill_hull, threshold,
edge, extension, tolerance, object_size, plot)
}
} else{
img2 <- help_binary(img,
index = index,
invert = invert,
opening = opening,
closing = closing,
filter = filter,
fill_hull = fill_hull,
threshold = threshold)
if(is.null(id)){
data_mask <- img2@.Data
coord <- t(as.matrix(bounding_box(data_mask, edge)))
colnames(coord) <- c("xleft", "xright", "ybottom", "ytop")
if(plot == TRUE){
plot(img)
rect(xleft = coord[1],
xright = coord[2],
ybottom = coord[3],
ytop = coord[4])
}
} else{
if(isTRUE(watershed)){
res <- length(img2)
parms <- read.csv(file=system.file("parameters.csv", package = "pliman", mustWork = TRUE), header = T, sep = ";")
parms2 <- parms[parms$object_size == object_size,]
rowid <-
which(sapply(as.character(parms2$resolution), function(x) {
eval(parse(text=x))}))
ext <- ifelse(is.null(extension), parms2[rowid, 3], extension)
tol <- ifelse(is.null(tolerance), parms2[rowid, 4], tolerance)
nmask <- EBImage::watershed(EBImage::distmap(img2),
tolerance = tol,
ext = ext)
} else{
nmask <- EBImage::bwlabel(img2)
}
data_mask <- nmask@.Data
ifelse(id == "all",
ids <- 1:max(data_mask),
ids <- id)
list_mask <- list()
for (i in ids) {
temp <- data_mask
temp[which(data_mask != i)] <- FALSE
list_mask[[i]] <- temp
}
list_mask <- list_mask[ids]
coord <- t(sapply(list_mask, bounding_box, edge))
colnames(coord) <- c("xleft", "xright", "ybottom", "ytop")
if(plot == TRUE){
plot(img)
rect(xleft = coord[,1],
xright = coord[,2],
ybottom = coord[,3],
ytop = coord[,4])
}
}
invisible(coord)
}
}
#' @name utils_objects
#' @inheritParams analyze_objects
#' @export
#'
object_contour <- function(img,
pattern = NULL,
dir_original = NULL,
center = FALSE,
index = "NB",
invert = FALSE,
opening = FALSE,
closing = FALSE,
filter = FALSE,
fill_hull = FALSE,
smooth = FALSE,
threshold = "Otsu",
watershed = TRUE,
extension = NULL,
tolerance = NULL,
object_size = "medium",
parallel = FALSE,
workers = NULL,
plot = TRUE,
verbose = TRUE){
if(is.null(dir_original)){
diretorio_original <- paste0("./")
} else{
diretorio_original <-
ifelse(grepl("[/\\]", dir_original),
dir_original,
paste0("./", dir_original))
}
if(is.null(pattern) && inherits(img, "list")){
if(!all(sapply(img, class) == "Image")){
stop("All images must be of class 'Image'")
}
if(parallel == TRUE){
nworkers <- ifelse(is.null(workers), trunc(parallel::detectCores()*.5), workers)
future::plan(future::multisession, workers = nworkers)
on.exit(future::plan(future::sequential))
`%dofut%` <- doFuture::`%dofuture%`
message("Image processing using multiple sessions (",nworkers, "). Please wait.")
foreach::foreach(i = seq_along(img)) %dofut%{
object_contour(img[[i]],
pattern, dir_original, center, index, invert, opening, closing, filter, fill_hull, smooth, threshold,
watershed, extension, tolerance, object_size, plot = plot)
}
} else{
lapply(img, object_contour, pattern, dir_original, center, index, invert, opening, closing, filter, fill_hull, smooth, threshold,
watershed, extension, tolerance, object_size, plot = plot)
}
} else{
if(is.null(pattern)){
img2 <- help_binary(img,
index = index,
invert = invert,
opening = opening,
closing = closing,
filter = filter,
fill_hull = fill_hull,
threshold = threshold)
if(isTRUE(watershed)){
res <- length(img2)
parms <- read.csv(file=system.file("parameters.csv", package = "pliman", mustWork = TRUE), header = T, sep = ";")
parms2 <- parms[parms$object_size == object_size,]
rowid <-
which(sapply(as.character(parms2$resolution), function(x) {
eval(parse(text=x))}))
ext <- ifelse(is.null(extension), parms2[rowid, 3], extension)
tol <- ifelse(is.null(tolerance), parms2[rowid, 4], tolerance)
nmask <- EBImage::watershed(EBImage::distmap(img2),
tolerance = tol,
ext = ext)
} else{
nmask <- EBImage::bwlabel(img2)
}
contour <- EBImage::ocontour(nmask)
if(isTRUE(center)){
contour <-
lapply(contour, function(x){
transform(x,
X1 = X1 - mean(X1),
X2 = X2 - mean(X2))
})
}
dims <- sapply(contour, function(x){dim(x)[1]})
contour <- contour[which(dims > mean(dims * 0.1))]
if(is.numeric(smooth) & smooth > 0){
contour <- poly_smooth(contour, niter = smooth, plot = FALSE) |> poly_close()
}
if(isTRUE(plot)){
if(isTRUE(center)){
plot_polygon(contour)
} else{
plot(img)
plot_contour(contour, col = "red")
}
}
invisible(contour)
} else{
if(pattern %in% c("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")){
pattern <- "^[0-9].*$"
}
plants <- list.files(pattern = pattern, diretorio_original)
extensions <- as.character(sapply(plants, file_extension))
names_plant <- as.character(sapply(plants, file_name))
if(length(grep(pattern, names_plant)) == 0){
stop(paste("Pattern '", pattern, "' not found in '",
paste(getwd(), sub(".", "", diretorio_original), sep = ""), "'", sep = ""),
call. = FALSE)
}
if(!all(extensions %in% c("png", "jpeg", "jpg", "tiff", "PNG", "JPEG", "JPG", "TIFF"))){
stop("Allowed extensions are .png, .jpeg, .jpg, .tiff")
}
help_contour <- function(img){
img <- image_import(img)
img2 <- help_binary(img,
index = index,
invert = invert,
opening = opening,
closing = closing,
filter = filter,
fill_hull = fill_hull,
threshold = threshold)
if(isTRUE(watershed)){
res <- length(img2)
parms <- read.csv(file=system.file("parameters.csv", package = "pliman", mustWork = TRUE), header = T, sep = ";")
parms2 <- parms[parms$object_size == object_size,]
rowid <-
which(sapply(as.character(parms2$resolution), function(x) {
eval(parse(text=x))}))
ext <- ifelse(is.null(extension), parms2[rowid, 3], extension)
tol <- ifelse(is.null(tolerance), parms2[rowid, 4], tolerance)
nmask <- EBImage::watershed(EBImage::distmap(img2),
tolerance = tol,
ext = ext)
} else{
nmask <- EBImage::bwlabel(img2)
}
contour <- EBImage::ocontour(nmask)
if(isTRUE(center)){
contour <-
lapply(contour, function(x){
transform(x,
X1 = X1 - mean(X1),
X2 = X2 - mean(X2))
})
}
dims <- sapply(contour, function(x){dim(x)[1]})
contour[which(dims > mean(dims * 0.1))]
}
if(parallel == TRUE){
init_time <- Sys.time()
nworkers <- ifelse(is.null(workers), trunc(parallel::detectCores()*.5), workers)
future::plan(future::multisession, workers = nworkers)
on.exit(future::plan(future::sequential))
`%dofut%` <- doFuture::`%dofuture%`
if(verbose == TRUE){
message("Processing ", length(names_plant), " images in multiple sessions (",nworkers, "). Please, wait.")
}
results <-
foreach::foreach(i = seq_along(plants)) %dofut%{
help_contour(plants[[i]])
}
} else{
pb <- progress(max = length(plants), style = 4)
foo <- function(plants, ...){
run_progress(pb, ...)
help_contour(plants)
}
results <-
lapply(seq_along(plants), function(i){
foo(plants[i],
actual = i,
text = paste("Processing image", names_plant[i]))
})
}
names(results) <- plants
invisible(results)
}
}
}
#' @name utils_objects
#' @export
object_isolate <- function(img,
id = NULL,
parallel = FALSE,
workers = NULL,
...){
if(inherits(img, "list")){
if(!all(sapply(img, class) == "Image")){
stop("All images must be of class 'Image'")
}
if(parallel == TRUE){
nworkers <- ifelse(is.null(workers), trunc(parallel::detectCores()*.5), workers)
future::plan(future::multisession, workers = nworkers)
on.exit(future::plan(future::sequential))
`%dofut%` <- doFuture::`%dofuture%`
message("Image processing using multiple sessions (",nworkers, "). Please wait.")
foreach::foreach(i = seq_along(img)) %dofut%{
object_isolate(img[[i]], id)
}
} else{
lapply(img, object_isolate, id, ...)
}
} else{
coord <- object_coord(img,
id = id,
plot = FALSE,
...)
segmented <- img[coord[1]:coord[2],
coord[3]:coord[4],
1:3]
invisible(segmented)
}
}
#' @name utils_objects
#' @export
object_id <- function(img,
parallel = FALSE,
workers = NULL,
...){
if(inherits(img, "list")){
if(!all(sapply(img, class) == "Image")){
stop("All images must be of class 'Image'")
}
if(parallel == TRUE){
nworkers <- ifelse(is.null(workers), trunc(parallel::detectCores()*.5), workers)
future::plan(future::multisession, workers = nworkers)
on.exit(future::plan(future::sequential))
`%dofut%` <- doFuture::`%dofuture%`
message("Image processing using multiple sessions (",nworkers, "). Please wait.")
foreach::foreach(i = seq_along(img)) %dofut%{
object_id(img[[i]], ...)
}
} else{
lapply(img, object_id, ...)
}
} else{
analyze_objects(img, verbose = FALSE, marker = "id", ...)
}
}
#' Splits objects from an image into multiple images
#'
#' Using threshold-based segmentation, objects are first isolated from
#' background. Then, a new image is created for each single object. A list of
#' images is returned.
#'
#' @inheritParams analyze_objects
#' @param lower_size Plant images often contain dirt and dust. To prevent dust from
#' affecting the image analysis, objects with lesser than 10% of the mean of all objects
#' are removed. Set `lower_limit = 0` to keep all the objects.
#' @param edge The number of pixels to be added in the edge of the segmented
#' object. Defaults to 5.
#' @param remove_bg If `TRUE`, the pixels that are not part of objects are
#' converted to white.
#' @param ... Additional arguments passed on to [image_combine()]
#' @return A list of objects of class `Image`.
#' @export
#' @seealso [analyze_objects()], [image_binary()]
#'
#' @examples
#' if (interactive() && requireNamespace("EBImage")) {
#' library(pliman)
#' img <- image_pliman("la_leaves.jpg", plot = TRUE)
#' imgs <- object_split(img) # set to NULL to use 50% of the cores
#' }
#'
object_split <- function(img,
index = "NB",
lower_size = NULL,
watershed = TRUE,
invert = FALSE,
fill_hull = FALSE,
opening = 3,
closing = FALSE,
filter = FALSE,
erode = FALSE,
dilate = FALSE,
threshold = "Otsu",
extension = NULL,
tolerance = NULL,
object_size = "medium",
edge = 3,
remove_bg = FALSE,
plot = TRUE,
verbose = TRUE,
...){
check_ebi()
img2 <- help_binary(img,
opening = opening,
closing = closing,
filter = filter,
erode = erode,
dilate = dilate,
index = index,
invert = invert,
fill_hull = fill_hull,
threshold = threshold)
if(isTRUE(watershed)){
parms <- read.csv(file=system.file("parameters.csv", package = "pliman", mustWork = TRUE), header = T, sep = ";")
res <- length(img2)
parms2 <- parms[parms$object_size == object_size,]
rowid <-
which(sapply(as.character(parms2$resolution), function(x) {
eval(parse(text=x))}))
ext <- ifelse(is.null(extension), parms2[rowid, 3], extension)
tol <- ifelse(is.null(tolerance), parms2[rowid, 4], tolerance)
nmask <- EBImage::watershed(EBImage::distmap(img2),
tolerance = tol,
ext = ext)
} else{
nmask <- EBImage::bwlabel(img2)
}
objcts <- get_area_mask(nmask)
av_area <- mean(objcts)
ifelse(!is.null(lower_size),
cutsize <- lower_size,
cutsize <- av_area * 0.1)
selected <- which(objcts > cutsize)
split_objects <- function(img, nmask){
objects <- help_isolate_object(img[,,1], img[,,2], img[,,3], nmask, remove_bg, edge)
lapply(seq_along(objects), function(x){
dimx <- dim(objects[[x]][[1]])
EBImage::Image(array(c(objects[[x]][[1]], objects[[x]][[2]], objects[[x]][[3]]), dim = c(dimx, 3)), colormode = "Color")
})
}
list_objects <- split_objects(img, nmask)
names(list_objects) <- 1:length(list_objects)
list_objects <- list_objects[selected]
if(isTRUE(verbose)){
cat("==============================\n")
cat("Summary of the procedure\n")
cat("==============================\n")
cat("Number of objects:", length(objcts), "\n")
cat("Average area :", mean(objcts), "\n")
cat("Minimum area :", min(objcts), "\n")
cat("Maximum area :", max(objcts), "\n")
cat("Objects created :", length(list_objects), "\n")
cat("==============================\n")
}
if(isTRUE(plot)){
image_combine(list_objects, ...)
}
invisible(list_objects)
}
#' Augment Images
#'
#' This function takes an image and augments it by rotating it multiple times.
#'
#' @param img An `Image` object.
#' @param pattern A regular expression pattern to select multiple images from a
#' directory.
#' @param times The number of times to rotate the image.
#' @param type The type of output: "export" to save images or "return" to return
#' a list of augmented images.
#' @param dir_original The directory where original images are located.
#' @param dir_processed The directory where processed images will be saved.
#' @param parallel Whether to perform image augmentation in parallel.
#' @param verbose Whether to display progress messages.
#'
#' @return If type is "export," augmented images are saved. If type is "return,"
#' a list of augmented images is returned.
#'
#' @export
#' @examples
#' if (interactive() && requireNamespace("EBImage")) {
#' library(pliman)
#' img <- image_pliman("sev_leaf.jpg")
#' imgs <- image_augment(img, type = "return", times = 4)
#' image_combine(imgs)
#' }
#'
image_augment <- function(img,
pattern = NULL,
times = 12,
type = "export",
dir_original = NULL,
dir_processed = NULL,
parallel = FALSE,
verbose = TRUE){
if(is.null(dir_original)){
diretorio_original <- paste0("./")
} else{
diretorio_original <-
ifelse(grepl("[/\\]", dir_original),
dir_original,
paste0("./", dir_original))
}
if(is.null(dir_processed)){
diretorio_processada <- paste0("./")
} else{
diretorio_processada <-
ifelse(grepl("[/\\]", dir_processed),
dir_processed,
paste0("./", dir_processed))
}
if(is.null(pattern)){
angles <- seq(0, 360, by = 360 / times)
angles <- angles[-length(angles)]
obj_list <- list()
for(i in 1:times){
top <- img@.Data[1:10,,]
bottom <- img@.Data[(nrow(img)-10):nrow(img),,]
left <- img@.Data[,1:10,]
right <- img@.Data[,(ncol(img) - 10):ncol(img),]
rval <- mean(c(c(top[,,1]), c(bottom[,,1]), c(left[,,1]), c(right[,,1])))
gval <- mean(c(c(top[,,2]), c(bottom[,,2]), c(left[,,2]), c(right[,,2])))
bval <- mean(c(c(top[,,3]), c(bottom[,,3]), c(left[,,3]), c(right[,,3])))
tmp <- EBImage::rotate(img, angles[i], bg.col = rgb(rval, gval, bval))
if(type == "export"){
image_export(tmp,
name = paste0("v", sub("\\.", "_", round(angles[i], 2)), ".jpg"),
subfolder = diretorio_processada)
} else{
obj_list[[paste0("v_", sub("\\.", "_", round(angles[i], 2)), ".jpg")]] <- tmp
}
}
} else{
if(is.null(dir_original)){
diretorio_original <- paste0("./")
} else{
diretorio_original <-
ifelse(grepl("[/\\]", dir_original),
dir_original,
paste0("./", dir_original))
}
if(is.null(dir_processed)){
diretorio_processada <- paste0("./")
} else{
diretorio_processada <-
ifelse(grepl("[/\\]", dir_processed),
dir_processed,
paste0("./", dir_processed))
}
if(pattern %in% c("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")){
pattern <- "^[0-9].*$"
}
plants <- list.files(pattern = pattern, diretorio_original)
extensions <- as.character(sapply(plants, file_extension))
names_plant <- as.character(sapply(plants, file_name))
if(length(grep(pattern, names_plant)) == 0){
stop(paste("Pattern '", pattern, "' not found in '",
paste(getwd(), sub(".", "", diretorio_original), sep = ""), "'", sep = ""),
call. = FALSE)
}
if(!all(extensions %in% c("png", "jpeg", "jpg", "tiff", "PNG", "JPEG", "JPG", "TIFF"))){
stop("Allowed extensions are .png, .jpeg, .jpg, .tiff")
}
if(isTRUE(parallel)){
init_time <- Sys.time()
nworkers <- trunc(parallel::detectCores()*.3)
future::plan(future::multisession, workers = nworkers)
on.exit(future::plan(future::sequential))
`%dofut%` <- doFuture::`%dofuture%`
if(verbose == TRUE){
message("Processing ", length(names_plant), " images in multiple sessions (",nworkers, "). Please, wait.")
}
obj_list <- list()
results <-
foreach::foreach(i = seq_along(plants)) %dofut%{
tmpimg <- image_import(plants[[i]], path = diretorio_original)
angles <- seq(0, 360, by = 360 / times)
angles <- angles[-length(angles)]
for(j in 1:times){
top <- tmpimg@.Data[1:10,,]
bottom <- tmpimg@.Data[(nrow(tmpimg)-10):nrow(tmpimg),,]
left <- tmpimg@.Data[,1:10,]
right <- tmpimg@.Data[,(ncol(tmpimg) - 10):ncol(tmpimg),]
rval <- mean(c(c(top[,,1]), c(bottom[,,1]), c(left[,,1]), c(right[,,1])))
gval <- mean(c(c(top[,,2]), c(bottom[,,2]), c(left[,,2]), c(right[,,2])))
bval <- mean(c(c(top[,,3]), c(bottom[,,3]), c(left[,,3]), c(right[,,3])))
tmp <- EBImage::rotate(tmpimg, angles[j], bg.col = rgb(rval, gval, bval))
if(type == "export"){
image_export(tmp,
name = paste0(file_name(plants[[j]]), "_", sub("\\.", "-", round(angles[j], 2)), ".jpg"),
subfolder = diretorio_processada)
} else{
obj_list[[paste0(file_name(plants[[j]]), "_", sub("\\.", "-", round(angles[j], 2)), ".jpg")]] <- tmp
}
}
}
message("Done!")
message("Elapsed time: ", sec_to_hms(as.numeric(difftime(Sys.time(), init_time, units = "secs"))))
} else{
obj_list <- list()
for(i in seq_along(plants)){
tmpimg <- image_import(plants[[i]], path = diretorio_original)
angles <- seq(0, 360, by = 360 / times)
angles <- angles[-length(angles)]
for(j in 1:times){
top <- tmpimg@.Data[1:10,,]
bottom <- tmpimg@.Data[(nrow(tmpimg)-10):nrow(tmpimg),,]
left <- tmpimg@.Data[,1:10,]
right <- tmpimg@.Data[,(ncol(tmpimg) - 10):ncol(tmpimg),]
rval <- mean(c(c(top[,,1]), c(bottom[,,1]), c(left[,,1]), c(right[,,1])))
gval <- mean(c(c(top[,,2]), c(bottom[,,2]), c(left[,,2]), c(right[,,2])))
bval <- mean(c(c(top[,,3]), c(bottom[,,3]), c(left[,,3]), c(right[,,3])))
tmp <- EBImage::rotate(tmpimg, angles[j], bg.col = rgb(rval, gval, bval))
if(type == "export"){
image_export(tmp,
name = paste0(file_name(plants[[i]]), "_", sub("\\.", "-", round(angles[j], 2)), ".jpg"),
subfolder = diretorio_processada)
} else{
obj_list[[paste0(file_name(plants[[i]]), "_", sub("\\.", "-", round(angles[j], 2)), ".jpg")]] <- tmp
}
}
}
}
}
if(type == "return"){
invisible(obj_list)
}
}
#' Export multiple objects from an image to multiple images
#'
#' Givin an image with multiple objects, `object_export()` will split the
#' objects into a list of objects using [object_split()] and then export them to
#' multiple images into the current working directory (or a subfolder). Batch
#' processing is performed by declaring a file name pattern that matches the
#' images within the working directory.
#'
#' @inheritParams object_split
#' @inheritParams utils_image
#' @inheritParams analyze_objects
#' @inheritParams image_augment
#'
#' @param pattern A pattern of file name used to identify images to be
#' processed. For example, if `pattern = "im"` all images in the current
#' working directory that the name matches the pattern (e.g., img1.-,
#' image1.-, im2.-) will be imported and processed. Providing any number as
#' pattern (e.g., `pattern = "1"`) will select images that are named as 1.-,
#' 2.-, and so on. An error will be returned if the pattern matches any file
#' that is not supported (e.g., img1.pdf).
#' @param augment A logical indicating if exported objects should be augmented using
#' [image_augment()]. Defaults to `FALSE`.
#'@param dir_original The directory containing the original images. Defaults to
#' `NULL`. It can be either a full path, e.g., `"C:/Desktop/imgs"`, or a
#' subfolder within the current working directory, e.g., `"/imgs"`.
#' @param dir_processed Optional character string indicating a subfolder within the
#' current working directory to save the image(s). If the folder doesn't
#' exist, it will be created.
#' @param format The format of image to be exported.
#' @param squarize Squarizes the image before the exportation? If `TRUE`,
#' [image_square()] will be called internally.
#' @return A `NULL` object.
#' @export
#'
#' @examples
#' if (interactive() && requireNamespace("EBImage")) {
#' library(pliman)
#' img <- image_pliman("potato_leaves.jpg")
#' object_export(img,
#' remove_bg = TRUE)
#' }
object_export <- function(img,
pattern = NULL,
dir_original = NULL,
dir_processed = NULL,
format = ".jpg",
squarize = FALSE,
augment = FALSE,
times = 12,
index = "NB",
lower_size = NULL,
watershed = FALSE,
invert = FALSE,
fill_hull = FALSE,
opening = 3,
closing = FALSE,
filter = FALSE,
erode = FALSE,
dilate = FALSE,
threshold = "Otsu",
extension = NULL,
tolerance = NULL,
object_size = "medium",
edge = 20,
remove_bg = FALSE,
parallel = FALSE,
verbose = TRUE){
if(is.null(pattern)){
list_objects <- object_split(img = img,
index = index,
lower_size = lower_size,
watershed = watershed,
invert = invert,
fill_hull = fill_hull,
opening = opening,
closing = closing,
erode = erode,
dilate = dilate,
filter = filter,
threshold = threshold,
extension = extension,
tolerance = tolerance,
object_size = object_size,
edge = edge,
remove_bg = remove_bg,
plot = FALSE,
verbose = FALSE)
names(list_objects) <- leading_zeros(as.numeric(names(list_objects)), n = 4)
if(isTRUE(augment)){
bb <-
lapply(seq_along(list_objects), function(x){
image_augment(list_objects[[x]], type = "return", times = times)
})
names(bb) <- names(list_objects)
unlisted <- do.call(c, bb)
names(unlisted) <- sub("\\.", "_", names(unlisted))
list_objects <- unlisted
}
a <- lapply(seq_along(list_objects), function(i){
tmp <- list_objects[[i]]
if(isTRUE(squarize)){
tmp <- image_square(tmp,
plot = FALSE,
sample_left = 5,
sample_top = 5,
sample_right = 5,
sample_bottom = 5)
}
image_export(tmp,
name = paste0(file_name(names(list_objects[i])), ".jpg"),
subfolder = dir_processed)
})
} else{
if(is.null(dir_original)){
diretorio_original <- paste0("./")
} else{
diretorio_original <-
ifelse(grepl("[/\\]", dir_original),
dir_original,
paste0("./", dir_original))
}
if(is.null(dir_processed)){
diretorio_processada <- paste0("./")
} else{
diretorio_processada <-
ifelse(grepl("[/\\]", dir_processed),
dir_processed,
paste0("./", dir_processed))
}
if(pattern %in% c("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")){
pattern <- "^[0-9].*$"
}
plants <- list.files(pattern = pattern, diretorio_original)
extensions <- as.character(sapply(plants, file_extension))
names_plant <- as.character(sapply(plants, file_name))
if(length(grep(pattern, names_plant)) == 0){
stop(paste("Pattern '", pattern, "' not found in '",
paste(getwd(), sub(".", "", diretorio_original), sep = ""), "'", sep = ""),
call. = FALSE)
}
if(!all(extensions %in% c("png", "jpeg", "jpg", "tiff", "PNG", "JPEG", "JPG", "TIFF"))){
stop("Allowed extensions are .png, .jpeg, .jpg, .tiff")
}
if(isTRUE(parallel)){
init_time <- Sys.time()
nworkers <- trunc(parallel::detectCores()*.3)
future::plan(future::multisession, workers = nworkers)
on.exit(future::plan(future::sequential))
`%dofut%` <- doFuture::`%dofuture%`
if(verbose == TRUE){
message("Processing ", length(names_plant), " images in multiple sessions (",nworkers, "). Please, wait.")
}
results <-
foreach::foreach(i = seq_along(plants)) %dofut%{
tmpimg <- image_import(plants[[i]], path = diretorio_original)
list_objects <- object_split(img = tmpimg,
index = index,
lower_size = lower_size,
watershed = watershed,
invert = invert,
fill_hull = fill_hull,
opening = opening,
closing = closing,
filter = filter,
threshold = threshold,
extension = extension,
tolerance = tolerance,
object_size = object_size,
edge = edge,
remove_bg = remove_bg,
verbose = FALSE,
plot = FALSE)
names(list_objects) <- paste0(leading_zeros(as.numeric(names(list_objects)), n = 4), ".jpg")
if(isTRUE(augment)){
bb <-
lapply(seq_along(list_objects), function(x){
image_augment(list_objects[[x]], type = "return", times = times)
})
names(bb) <- names(list_objects)
unlisted <- do.call(c, bb)
names(unlisted) <- sub("\\.", "_", names(unlisted))
list_objects <- unlisted
names(list_objects) <- sub("jpg.", "", names(list_objects))
}
a <- lapply(seq_along(list_objects), function(j){
tmp <- list_objects[[j]]
if(isTRUE(squarize)){
try(
tmp <- image_square(tmp,
plot = FALSE,
sample_left = 5,
sample_top = 5,
sample_right = 5,
sample_bottom = 5),
silent = TRUE
)
}
image_export(tmp,
name = paste0(file_name(plants[[i]]), "_", names(list_objects[j])),
subfolder = diretorio_processada)
}
)
}
message("Done!")
message("Elapsed time: ", sec_to_hms(as.numeric(difftime(Sys.time(), init_time, units = "secs"))))
} else{
for(i in seq_along(plants)){
tmpimg <- image_import(plants[[i]], path = diretorio_original)
list_objects <- object_split(img = tmpimg,
index = index,
lower_size = lower_size,
watershed = watershed,
invert = invert,
fill_hull = fill_hull,
opening = opening,
closing = closing,
filter = filter,
threshold = threshold,
extension = extension,
tolerance = tolerance,
object_size = object_size,
edge = edge,
remove_bg = remove_bg,
verbose = FALSE,
plot = FALSE)