-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils_imagem.R
4301 lines (4173 loc) · 152 KB
/
utils_imagem.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
#'Combines images to a grid
#'
#'Combines several images to a grid
#' @param ... a comma-separated name of image objects or a list containing image
#' objects.
#' @param labels A character vector with the same length of the number of
#' objects in `...` to indicate the plot labels.
#' @param nrow,ncol The number of rows or columns in the plot grid. Defaults to
#' `NULL`, i.e., a square grid is produced.
#' @param col The color for the plot labels. Defaults to `col = "black"`.
#' @param verbose Shows the name of objects declared in `...` or a numeric
#' sequence if a list with no names is provided. Set to `FALSE` to supress the
#' text.
#' @importFrom stats reshape IQR quantile
#' @export
#' @author Tiago Olivoto \email{tiagoolivoto@@gmail.com}
#' @return A grid with the images in `...`
#' @examples
#' if (interactive() && requireNamespace("EBImage")) {
#' library(pliman)
#' img1 <- image_pliman("sev_leaf.jpg")
#' img2 <- image_pliman("sev_leaf_nb.jpg")
#' image_combine(img1, img2)
#' }
image_combine <- function(...,
labels = NULL,
nrow = NULL,
ncol = NULL,
col = "black",
verbose = TRUE){
if(is.list(c(...))){
plots <- as.list(...)
if(class(plots) %in% c("binary_list", "segment_list", "index_list",
"img_mat_list", "palette_list")){
plots <- lapply(plots, function(x){x[[1]]})
}
if(!is.null(labels)){
names(plots) <- labels
}
}else{
plots <- list(...)
if(is.null(labels)){
names(plots) <- unlist(strsplit(gsub("c\\(|\\)", "", substitute(c(...))), "\\s*(\\s|,)\\s*"))[-1]
} else{
names(plots) <- labels
}
}
num_plots <- length(plots)
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))
ifelse(is.null(names(plots)), index <- 1:length(plots), index <- names(plots))
for(i in 1:length(plots)){
plot(plots[[i]])
if(verbose == TRUE){
dim <- image_dimension(plots[[i]], verbose = FALSE)
text(0, dim[[2]]*0.075, index[[i]], pos = 4, col = col)
}
}
}
#'Import and export images
#'
#'Import images from files and URLs and write images to files, possibly with
#'batch processing.
#' @name utils_image
#' @param img
#' * For `image_import()`, a character vector of file names or URLs.
#' * For `image_input()`, a character vector of file names or URLs or an array
#' containing the pixel intensities of an image.
#' * For `image_export()`, an Image object, an array or a list of images.
#' * For `image_pliman()`, a charactere value specifying the image example. See
#' `?pliman_images` for more details.
#' @param which logical scalar or integer vector to indicate which image are
#' imported if a TIFF files is informed. Defaults to `1` (the first image is
#' returned).
#' @param name An string specifying the name of the image. It can be either a
#' character with the image name (e.g., "img1") or name and extension (e.g.,
#' "img1.jpg"). If none file extension is provided, the image will be saved as
#' a *.jpg file.
#' @param prefix A prefix to include in the image name when exporting a list of
#' images. Defaults to `""`, i.e., no prefix.
#' @param extension When `image` is a list, `extension` can be used to define
#' the extension of exported files. This will overwrite the file extensions
#' given in `image`.
#' @param pattern A pattern of file name used to identify images to be imported.
#' 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 as a list. 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 subfolder 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 path A character vector of full path names; the default corresponds to
#' the working directory, [getwd()]. It will overwrite (if given) the path
#' informed in `image` argument.
#' @param resize Resize the image after importation? Defaults to `FALSE`. Use a
#' numeric value of range 0-100 (proportion of the size of the original
#' image).
#' @param plot Plots the image after importing? Defaults to `FALSE`.
#' @param nrow,ncol Passed on to [image_combine()]. The number of rows and
#' columns to use in the composite image when `plot = TRUE`.
#' @param ...
#' * For `image_import()` alternative arguments passed to the corresponding
#' functions from the `jpeg`, `png`, and `tiff` packages.
#' * For `image_input()` further arguments passed on to [EBImage::Image()].
#' @md
#' @export
#' @author Tiago Olivoto \email{tiagoolivoto@@gmail.com}
#' @return
#' * `image_import()` returns a new `Image` object.
#' * `image_export()` returns an invisible vector of file names.
#' * `image_pliman()` returns a new `Image` object with the example image
#' required. If an empty call is used, the path to the `tmp_images` directory
#' installed with the package is returned.
#' @examples
#' if (interactive() && requireNamespace("EBImage")) {
#' library(pliman)
#' folder <- image_pliman()
#' full_path <- paste0(folder, "/sev_leaf.jpg")
#' (path <- file_dir(full_path))
#' (file <- basename(full_path))
#' image_import(img = full_path)
#' image_import(img = file, path = path)
#' }
image_import <- function(img,
...,
which = 1,
pattern = NULL,
path = NULL,
resize = FALSE,
plot = FALSE,
nrow = NULL,
ncol = NULL){
check_ebi()
valid_extens <- c("png", "jpeg", "jpg", "tiff", "PNG", "JPEG", "JPG", "TIFF", "TIF", "tif", "gri", "grd")
if(!is.null(pattern)){
if(pattern %in% c("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")){
pattern <- "^[0-9].*$"
}
path <- ifelse(is.null(path), getwd(), path)
imgs <- list.files(pattern = pattern, path)
if(length(grep(pattern, imgs)) == 0){
stop(paste("'", pattern, "' pattern not found in '",
paste0(dir)),
call. = FALSE)
}
extensions <- as.character(sapply(imgs, file_extension))
all_valid <- extensions %in% valid_extens
if(any(all_valid == FALSE)){
warning("'", paste(imgs[which(all_valid == FALSE)], collapse = ", "),
"' of invalid format ignored.", call. = FALSE)
}
imgs <- paste0(path, "/", imgs[all_valid])
list_img <-
lapply(imgs, function(x){
EBImage::readImage(x)
})
names(list_img) <- basename(imgs)
if(isTRUE(plot)){
image_combine(list_img, nrow = nrow, ncol = ncol)
}
if(resize != FALSE){
if(!is.numeric(resize)){
stop("Argument `resize` must be numeric.", call. = FALSE)
}
list_img <- image_resize(list_img, resize)
}
invisible(list_img)
} else{
img_dir <- ifelse(is.null(path), file_dir(img), path)
all_files <- sapply(list.files(img_dir), file_name)
img_name <- file_name(img)
test <- img_name %in% file_name(list.files(img_dir))
if(!any(grepl("http", img_dir, fixed = TRUE)) & !all(test)){
stop(" '",img_name[which(test == FALSE)],"' not found in ", img_dir[which(test == FALSE)], call. = FALSE)
}
fext <- file_extension(img)
img_name <- paste0(img_dir, "/", img_name , ".", fext[length(fext)])
if(length(img) > 1){
ls <-
lapply(seq_along(img_name),
function(x){
fext <- file_extension(img_name[[1]])
if(fext[length(fext)] %in% c("tif", "TIF", "tiff", "TIFF", "gri", "grd")){
terra::rast(img_name[x])
} else{
EBImage::readImage(img_name[x], ...)
}
})
names(ls) <- basename(img_name)
if(isTRUE(plot)){
image_combine(ls, nrow = nrow, ncol = ncol)
}
if(resize != FALSE){
if(!is.numeric(resize)){
stop("Argument `resize` must be numeric.", call. = FALSE)
}
ls <- image_resize(ls, resize)
}
invisible(ls)
} else{
fext <- file_extension(img_name)
if(fext[length(fext)] %in% c("tif", "TIF", "tiff", "TIFF", "gri", "grd")){
img <- terra::rast(img_name)
} else{
img <- EBImage::readImage(img_name, ...)
}
if(isTRUE(plot)){
plot(img)
}
if(resize != FALSE){
if(!is.numeric(resize)){
stop("Argument `resize` must be numeric.", call. = FALSE)
}
img <- image_resize(img, resize)
}
invisible(img)
}
}
}
#' @export
#' @name utils_image
image_export <- function(img,
name,
prefix = "",
extension = NULL,
subfolder = NULL,
...){
check_ebi()
if(class(img) %in% c("binary_list", "index_list",
"img_mat_list", "palette_list")){
img <- lapply(img, function(x){x[[1]]})
}
if(inherits(img, "segment_list")){
img <- lapply(img, function(x){x[[1]][[1]]})
}
if(is.list(img)){
if(!all(sapply(img, class) == "Image")){
stop("All images must be of class 'Image'")
}
name <- file_name(names(img))
extens <- file_extension(names(img))
if(any(sapply(extens, length)) == 0 & is.null(extension)){
extens <- rep("jpg", length(img))
message("Image(s) exported as *.jpg file(s).")
}
if(!is.null(extension)){
extens <- rep(extension, length(img))
}
names(img) <- paste0(name, ".", extens)
if(!missing(subfolder)){
dir_out <- paste0(getwd(), "/", subfolder)
if(dir.exists(dir_out) == FALSE){
dir.create(dir_out, recursive = TRUE)
}
names(img) <- paste0(dir_out, "/", prefix, name, ".", extens)
a <-
lapply(seq_along(img), function(i){
EBImage::writeImage(x = img[[i]], files = names(img[i]), ...)
})
} else{
a <-
lapply(seq_along(img), function(i){
EBImage::writeImage(x = img[[i]], files = paste0(prefix, names(img[i])), ...)
})
}
} else{
filname <- file_name(name)
extens <- unlist(file_extension(name))
dir_out <- file_dir(name)
if(length(extens) == 1){
extens <- extens
} else if(length(extens) == 0 & is.null(extension)){
extens <- "jpg"
message("Image(s) exported as *.jpg file(s).")
} else if(!is.null(extension)){
extens <- extension
}
if(!missing(subfolder) & nchar(dir_out) == 2){
dir_out <- paste0("./", subfolder)
}
if(dir.exists(dir_out) == FALSE){
dir.create(dir_out, recursive = TRUE)
}
name <- paste0(dir_out, "/", filname, ".", extens)
EBImage::writeImage(img, name)
}
}
#' @export
#' @name utils_image
image_input <- function(img, ...){
check_ebi()
if(inherits(img, "character")){
image_import(img, ...)
} else if(inherits(img, "array")){
range <- apply(img, 3, max)
if(any(range > 1)){
EBImage::Image(img / 255, colormode = "color")
} else{
EBImage::Image(img, colormode = "color")
}
}
}
#' @export
#' @name utils_image
image_pliman <- function(img, plot = FALSE){
check_ebi()
path <- system.file("tmp_images", package = "pliman")
files <- list.files(path)
if(!missing(img)){
if(!img %in% files){
stop("Image not available in pliman.\nAvaliable images: ", paste(files, collapse = ", "), call. = FALSE)
}
im <- image_import(system.file(paste0("tmp_images/", img), package = "pliman"))
if(isTRUE(plot)){
plot(im)
}
invisible(im)
} else{
path
}
}
##### Spatial transformations
#'Spatial transformations
#'
#' Performs image rotation and reflection
#' * `image autocrop()` Crops automatically an image to the area of objects.
#' * `image_crop()` Crops an image to the desired area.
#' * `image_trim()` Remove pixels from the edges of an image (20 by default).
#' * `image_dimension()` Gives the dimension (width and height) of an image.
#' * `image_rotate()` Rotates the image clockwise by the given angle.
#' * `image_horizontal()` Converts (if needed) an image to a horizontal image.
#' * `image_vertical()` Converts (if needed) an image to a vertical image.
#' * `image_hreflect()` Performs horizontal reflection of the `image`.
#' * `image_vreflect()` Performs vertical reflection of the `image`.
#' * `image_resize()` Resize the `image`. See more at [EBImage::resize()].
#' * `image_contrast()` Improve contrast locally by performing adaptive
#' histogram equalization. See more at [EBImage::clahe()].
#' * `image_dilate()` Performs image dilatation. See more at [EBImage::dilate()].
#' * `image_erode()` Performs image erosion. See more at [EBImage::erode()].
#' * `image_opening()` Performs an erosion followed by a dilation. See more at
#' [EBImage::opening()].
#' * `image_closing()` Performs a dilation followed by an erosion. See more at
#' [EBImage::closing()].
#' * `image_filter()` Performs median filtering in constant time. See more at
#' [EBImage::medianFilter()].
#' * `image_blur()` Performs blurring filter of images. See more at
#' [EBImage::gblur()].
#' * `image_skeleton()` Performs image skeletonization.
#'
#'
#' @name utils_transform
#' @inheritParams image_view
#' @param img An image or a list of images of class `Image`.
#' @param index The index to segment the image. See [image_index()] for more
#' details. Defaults to `"NB"` (normalized blue).
#' @param viewer The viewer option. If not provided, the value is retrieved
#' using [get_pliman_viewer()]. This option controls the type of viewer to use
#' for interactive plotting. The available options are "base" and "mapview".
#' If set to "base", the base R graphics system is used for interactive
#' plotting. If set to "mapview", the mapview package is used. To set this
#' argument globally for all functions in the package, you can use the
#' [set_pliman_viewer()] function. For example, you can run
#' `set_pliman_viewer("mapview")` to set the viewer option to "mapview" for
#' all functions.
#' @param show How to plot in mapview viewer, either `"rgb"` or `"index"`.
#' @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 70% 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 edge
#' * for [image_autocrop()] the number of pixels in the edge of the cropped
#' image. If `edge = 0` the image will be cropped to create a bounding rectangle
#' (x and y coordinates) around the image objects.
#' * for [image_trim()], the number of pixels removed from the edges. By
#' default, 20 pixels are removed from all the edges.
#' @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 top,bottom,left,right The number of pixels removed from `top`,
#' `bottom`, `left`, and `right` when using [image_trim()].
#' @param angle The rotation angle in degrees.
#' @param bg_col Color used to fill the background pixels, defaults to `"white"`.
#' @param rel_size The relative size of the resized image. Defaults to 100. For
#' example, setting `rel_size = 50` to an image of width `1280 x 720`, the new
#' image will have a size of `640 x 360`.
#' @param width,height
#' * For `image_resize()` the Width and height of the resized image. These arguments
#' can be missing. In this case, the image is resized according to the
#' relative size informed in `rel_size`.
#' * For `image_crop()` a numeric vector indicating the pixel range (x and y,
#' respectively) that will be maintained in the cropped image, e.g., width =
#' 100:200
#' @param kern An `Image` object or an array, containing the structuring
#' element. Defaults to a brushe generated with [EBImage::makeBrush()].
#' @param niter The number of iterations to perform in the thinning procedure.
#' Defaults to 3. Set to `NULL` to iterate until the binary image is no longer
#' changing.
#' @param shape A character vector indicating the shape of the brush. Can be
#' `box`, `disc`, `diamond`, `Gaussian` or `line`. Default is `disc`.
#' @param size
#' * For `image_filter()` is the median filter radius (integer). Defaults to `3`.
#' * For `image_dilate()` and `image_erode()` is an odd number containing the
#' size of the brush in pixels. Even numbers are rounded to the next odd one.
#' The default depends on the image resolution and is computed as the image
#' resolution (megapixels) times 20.
#' @param sigma A numeric denoting the standard deviation of the Gaussian filter
#' used for blurring. Defaults to `3`.
#' @param cache The the L2 cache size of the system CPU in kB (integer).
#' Defaults to `512`.
#' @param verbose If `TRUE` (default) a summary is shown in the console.
#' @param plot If `TRUE` plots the modified image. Defaults to `FALSE`.
#' @param ... Additional arguments passed on to [image_binary()].
#' @md
#' @export
#' @author Tiago Olivoto \email{tiagoolivoto@@gmail.com}
#' @return
#' * `image_skeleton()` returns a binary `Image` object.
#' * All other functions returns a modified version of `image` depending on the
#' `image_*()` function used.
#' * If `image` is a list, a list of the same length will be returned.
#' @examples
#' if (interactive() && requireNamespace("EBImage")) {
#' library(pliman)
#'img <- image_pliman("sev_leaf.jpg")
#'plot(img)
#'img <- image_resize(img, 50)
#'img1 <- image_rotate(img, 45)
#'img2 <- image_hreflect(img)
#'img3 <- image_vreflect(img)
#'img4 <- image_vertical(img)
#'image_combine(img1, img2, img3, img4)
#' }
image_autocrop <- function(img,
index = "NB",
edge = 5,
opening = 5,
closing = FALSE,
filter = FALSE,
parallel = FALSE,
workers = NULL,
verbose = TRUE,
plot = FALSE){
check_ebi()
if(is.list(img)){
if(class(img) %in% c("binary_list", "segment_list", "index_list",
"img_mat_list", "palette_list")){
img <- lapply(img, function(x){x[[1]]})
}
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()*.4), workers)
future::plan(future::multisession, workers = nworkers)
on.exit(future::plan(future::sequential))
`%dofut%` <- doFuture::`%dofuture%`
if(verbose == TRUE){
message("Image processing using multiple sessions (",nworkers, "). Please wait.")
}
res <-
foreach::foreach(i = seq_along(img)) %dofut%{
image_autocrop(img[[i]], index, edge)
}
} else{
res <- lapply(img, image_autocrop, index, edge)
}
invisible(structure(res, class = "autocrop_list"))
} else{
conv_hull <- object_coord(img,
index = index,
id = NULL,
edge = edge,
plot = FALSE,
opening = opening,
closing = closing,
filter = filter)
segmented <- img[conv_hull[1]:conv_hull[2],
conv_hull[3]:conv_hull[4],
1:3]
if(isTRUE(plot)){
plot(segmented)
}
invisible(segmented)
}
}
#' @name utils_transform
#' @export
image_crop <- function(img,
width = NULL,
height = NULL,
viewer = get_pliman_viewer(),
downsample = NULL,
max_pixels = 1000000,
show = "rgb",
parallel = FALSE,
workers = NULL,
verbose = TRUE,
plot = FALSE){
vieweropt <- c("base", "mapview")
vieweropt <- vieweropt[pmatch(viewer[1], vieweropt)]
if(is.list(img)){
if(class(img) %in% c("binary_list", "segment_list", "index_list",
"img_mat_list", "palette_list")){
img <- lapply(img, function(x){x[[1]]})
}
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()*.4), workers)
future::plan(future::multisession, workers = nworkers)
on.exit(future::plan(future::sequential))
`%dofut%` <- doFuture::`%dofuture%`
if(verbose == TRUE){
message("Image processing using multiple sessions (",nworkers, "). Please wait.")
}
res <-
foreach::foreach(i = seq_along(img)) %dofut%{
image_crop(img[[i]], width, height, viewer, downsample, max_pixels)
}
} else{
res <- lapply(img, image_crop, width, height, viewer, downsample, max_pixels)
}
invisible(res)
} else{
if (!is.null(width) | !is.null(height)) {
dim <- dim(img)[1:2]
if (!is.null(width) & is.null(height)) {
height <- 1:dim[2]
}
if (is.null(width) & !is.null(height)) {
width <- 1:dim[1]
}
if(!is.null(height) & !is.null(width)){
width <- width
height <- height
}
if (!is.numeric(width) | !is.numeric(height)) {
stop("Vectors must be numeric.")
}
img@.Data <- img@.Data[width, height, ]
}
if (is.null(width) & is.null(height)) {
if(vieweropt == "base"){
message("Use the left mouse buttom to crop the image.")
if(EBImage::numberOfFrames(img) > 2){
plot(EBImage::Image(img[,,1:3], colormode = "Color"))
} else if(EBImage::numberOfFrames(img) == 1){
plot(img)
}
cord <- locator(type = "p", n = 2, col = "red", pch = 19)
minw <- min(cord$x[[1]], cord$x[[2]])
maxw <- max(cord$x[[1]], cord$x[[2]])
minh <- min(cord$y[[1]], cord$y[[2]])
maxh <- max(cord$y[[1]], cord$y[[2]])
w <- round(minw, 0):round(maxw, 0)
h <- round(minh, 0):round(maxh, 0)
} else{
nc <- ncol(img)
mv <- mv_rectangle(img, show = show, downsample = downsample, max_pixels = max_pixels)
w <- round(min(mv[,1]):max(mv[,1]))
h <- round((min(mv[,2]))):round(max(mv[,2]))
}
img@.Data <- img@.Data[w, h, ]
if(isTRUE(verbose)){
cat(paste0("width = ", w[1], ":", w[length(w)]), "\n")
cat(paste0("height = ", h[1], ":", h[length(h)]), "\n")
}
}
if (isTRUE(plot)) {
if(EBImage::numberOfFrames(img) > 2){
plot(EBImage::Image(img[,,1:3], colormode = "Color"))
} else if(EBImage::numberOfFrames(img) == 1){
plot(img)
}
}
invisible(img)
}
}
#' @name utils_transform
#' @export
image_dimension <- function(img,
parallel = FALSE,
workers = NULL,
verbose = TRUE){
if(is.list(img)){
if(class(img) %in% c("binary_list", "segment_list", "index_list",
"img_mat_list", "palette_list")){
img <- lapply(img, function(x){x[[1]]})
}
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()*.4), workers)
future::plan(future::multisession, workers = nworkers)
on.exit(future::plan(future::sequential))
`%dofut%` <- doFuture::`%dofuture%`
if(verbose == TRUE){
message("Image processing using multiple sessions (",nworkers, "). Please wait.")
}
res <-
as.data.frame(
do.call(rbind,
foreach::foreach(i = seq_along(img)) %dofut%{
image_dimension(img[[i]], verbose = FALSE)
}
)
)
res <- transform(res, image = rownames(res))[,c(3, 1, 2)]
} else{
res <-
do.call(rbind,
lapply(img, function(x){
dim <- image_dimension(x, verbose = FALSE)
data.frame(width = dim[[1]],
height = dim[[2]])
}))
res <- transform(res, image = rownames(res))[,c(3, 1, 2)]
rownames(res) <- NULL
}
if(verbose == TRUE){
cat("\n----------------------\n")
cat("Image dimension\n")
cat("----------------------\n")
print(res, row.names = FALSE)
cat("\n")
}
invisible(res)
} else{
width <- dim(img)[[1]]
height <- dim(img)[[2]]
if(verbose == TRUE){
cat("\n----------------------\n")
cat("Image dimension\n")
cat("----------------------\n")
cat("Width : ", width, "\n")
cat("Height: ", height, "\n")
cat("\n")
}
invisible(list(width = width, height = height))
}
}
#' @name utils_transform
#' @export
image_rotate <- function(img,
angle,
bg_col = "white",
parallel = FALSE,
workers = NULL,
verbose = TRUE,
plot = TRUE){
check_ebi()
if(is.list(img)){
if(class(img) %in% c("binary_list", "segment_list", "index_list",
"img_mat_list", "palette_list")){
img <- lapply(img, function(x){x[[1]]})
}
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()*.4), workers)
future::plan(future::multisession, workers = nworkers)
on.exit(future::plan(future::sequential))
`%dofut%` <- doFuture::`%dofuture%`
if(verbose == TRUE){
message("Image processing using multiple sessions (",nworkers, "). Please wait.")
}
res <-
foreach::foreach(i = seq_along(img)) %dofut%{
image_rotate(img[[i]], angle, bg_col)
}
} else{
lapply(img, image_rotate, angle, bg_col)
}
} else{
img <- EBImage::rotate(img, angle, bg.col = bg_col)
if (isTRUE(plot) & EBImage::numberOfFrames(img) > 2) {
plot(EBImage::Image(img[,,1:3], colormode = "Color"))
}
invisible(img)
}
}
#' @name utils_transform
#' @export
image_horizontal <- function(img,
parallel = FALSE,
workers = NULL,
verbose = TRUE,
plot = FALSE){
check_ebi()
if(is.list(img)){
if(class(img) %in% c("binary_list", "segment_list", "index_list",
"img_mat_list", "palette_list")){
img <- lapply(img, function(x){x[[1]]})
}
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()*.4), workers)
future::plan(future::multisession, workers = nworkers)
on.exit(future::plan(future::sequential))
`%dofut%` <- doFuture::`%dofuture%`
if(verbose == TRUE){
message("Image processing using multiple sessions (",nworkers, "). Please wait.")
}
foreach::foreach(i = seq_along(img)) %dofut%{
image_horizontal(img[[i]])
}
} else{
lapply(img, image_horizontal)
}
} else{
width <- dim(img)[[1]]
height <- dim(img)[[2]]
if(width < height){
img <- EBImage::rotate(img, 90)
} else{
img <- img
}
if (isTRUE(plot)) {
plot(img)
}
invisible(img)
}
}
#' @name utils_transform
#' @export
image_vertical <- function(img,
parallel = FALSE,
workers = NULL,
verbose = TRUE,
plot = FALSE){
check_ebi()
if(is.list(img)){
if(class(img) %in% c("binary_list", "segment_list", "index_list",
"img_mat_list", "palette_list")){
img <- lapply(img, function(x){x[[1]]})
}
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()*.4), workers)
future::plan(future::multisession, workers = nworkers)
on.exit(future::plan(future::sequential))
`%dofut%` <- doFuture::`%dofuture%`
if(verbose == TRUE){
message("Image processing using multiple sessions (",nworkers, "). Please wait.")
}
foreach::foreach(i = seq_along(img)) %dofut%{
image_vertical(img[[i]])
}
} else{
lapply(img, image_vertical)
}
} else{
width <- dim(img)[[1]]
height <- dim(img)[[2]]
if(width > height){
img <- EBImage::rotate(img, 90)
} else{
img <- img
}
if (isTRUE(plot)) {
plot(img)
}
invisible(img)
}
}
#' @name utils_transform
#' @export
image_hreflect <- function(img,
parallel = FALSE,
workers = NULL,
verbose = TRUE,
plot = FALSE){
check_ebi()
if(is.list(img)){
if(class(img) %in% c("binary_list", "segment_list", "index_list",
"img_mat_list", "palette_list")){
img <- lapply(img, function(x){x[[1]]})
}
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()*.4), workers)
future::plan(future::multisession, workers = nworkers)
on.exit(future::plan(future::sequential))
`%dofut%` <- doFuture::`%dofuture%`
if(verbose == TRUE){
message("Image processing using multiple sessions (",nworkers, "). Please wait.")
}
foreach::foreach(i = seq_along(img)) %dofut%{
image_hreflect(img[[i]])
}
} else{
lapply(img, image_hreflect)
}
} else{
img <- EBImage::flop(img)
if (isTRUE(plot)) {
plot(img)
}
invisible(img)
}
}
#' @name utils_transform
#' @export
image_vreflect <- function(img,
parallel = FALSE,
workers = NULL,
verbose = TRUE,
plot = FALSE){
check_ebi()
if(is.list(img)){
if(class(img) %in% c("binary_list", "segment_list", "index_list",
"img_mat_list", "palette_list")){
img <- lapply(img, function(x){x[[1]]})
}
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()*.4), workers)
future::plan(future::multisession, workers = nworkers)
on.exit(future::plan(future::sequential))
`%dofut%` <- doFuture::`%dofuture%`
if(verbose == TRUE){
message("Image processing using multiple sessions (",nworkers, "). Please wait.")
}
foreach::foreach(i = seq_along(img)) %dofut%{
image_vreflect(img[[i]])
}
} else{
lapply(img, image_vreflect)
}
} else{
img <- EBImage::flip(img)
if (isTRUE(plot)) {
plot(img)
}
invisible(img)
}
}
#' @name utils_transform
#' @export
image_resize <- function(img,
rel_size = 100,
width,
height,
parallel = FALSE,
workers = NULL,
verbose = TRUE,
plot = FALSE){
check_ebi()
if(is.list(img)){
if(class(img) %in% c("binary_list", "segment_list", "index_list",
"img_mat_list", "palette_list")){
img <- lapply(img, function(x){x[[1]]})
}
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()*.4), workers)
future::plan(future::multisession, workers = nworkers)
on.exit(future::plan(future::sequential))
`%dofut%` <- doFuture::`%dofuture%`
if(verbose == TRUE){
message("Image processing using multiple sessions (",nworkers, "). Please wait.")
}
foreach::foreach(i = seq_along(img)) %dofut%{
image_resize(img[[i]], rel_size)
}
} else{
lapply(img, image_resize, rel_size, width, height)
}
} else{
nrow <- dim(img)[[1]]
new_row <- nrow * rel_size / 100
width <- ifelse(missing(width), new_row, width)
img <- EBImage::resize(img, width, height)
if (isTRUE(plot)) {
plot(img)
}
invisible(img)
}
}
#' @name utils_transform
#' @export
image_trim <- function(img,
edge = NULL,
top = NULL,
bottom = NULL,
left = NULL,
right = NULL,
parallel = FALSE,
workers = NULL,
verbose = TRUE,
plot = FALSE){
check_ebi()
if(is.null(edge) & all(sapply(list(top, bottom, left, right), is.null))){
edge <- 20
}
if(is.null(edge) & !all(sapply(list(top, bottom, left, right), is.null))){
edge <- 0
}
top <- ifelse(is.null(top), edge, top)
bottom <- ifelse(is.null(bottom), edge, bottom)
left <- ifelse(is.null(left), edge, left)
right <- ifelse(is.null(right), edge, right)
if(is.list(img)){
if(class(img) %in% c("binary_list", "segment_list", "index_list",
"img_mat_list", "palette_list")){
img <- lapply(img, function(x){x[[1]]})
}
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()*.4), workers)
future::plan(future::multisession, workers = nworkers)
on.exit(future::plan(future::sequential))
`%dofut%` <- doFuture::`%dofuture%`
if(verbose == TRUE){
message("Image processing using multiple sessions (",nworkers, "). Please wait.")
}
foreach::foreach(i = seq_along(img)) %dofut%{
image_trim(img[[i]], edge, top, bottom, left, right)
}
} else{
lapply(img, image_trim, edge, top, bottom, left, right)
}
} else{
img <- img[, -c(1:top) ,]
img <- img[, -c((dim(img)[2] - bottom + 1):dim(img)[2]) ,]
img <- img[-c((dim(img)[1] - right + 1):dim(img)[1]) , ,]
img <- img[-c(1:left), ,]
if (isTRUE(plot)) {
plot(img)
}
invisible(img)
}
}
#' @name utils_transform
#' @export
image_dilate <- function(img,
kern = NULL,
size = NULL,
shape = "disc",
parallel = FALSE,
workers = NULL,
verbose = TRUE,
plot = FALSE){
check_ebi()
if(is.list(img)){