-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
open_image_rscript.R
1475 lines (1092 loc) · 47.2 KB
/
open_image_rscript.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
#' gaussian-kernel
#'
#' @keywords internal
gaussian_kernel = function(xy_length = 2, sigma = 1.0, range_gauss = 2) {
if (xy_length < 1 || !is.numeric(xy_length)) {
stop('xy_length should be an integer greater than 0')
}
if (range_gauss <= 0.0) {
stop("the 'range_gauss' should be a positive number")
}
gaussian_formula = function(x, y) 1/(2 * pi * (sigma ^ 2)) * (exp(-(x ^ 2 + y ^ 2)/(2 * sigma ^ 2)))
tmp_seq = seq(-range_gauss, range_gauss, length = xy_length)
tmp_outer = outer(tmp_seq, tmp_seq, gaussian_formula)
return(tmp_outer/sum(tmp_outer))
}
#' Normalize a matrix to specific range of values
#'
#' @param data a matrix
#' @param min_value the new minimum value for the input \emph{data}
#' @param max_value the new maximum value for the input \emph{data}
#' @return a matrix
#' @export
#' @examples
#'
#' set.seed(1)
#' mt = matrix(1:48, 8, 6)
#'
#' res = norm_matrix_range(mt, min_value = -1, max_value = 1)
#'
norm_matrix_range = function(data, min_value = -1, max_value = 1) {
if (!inherits(data, 'matrix')) {
stop('data should be a matrix')
}
MIN = min(data)
data = (data - MIN) / (max(data) - MIN)
rng = min_value - max_value
out = min_value - data * rng
return(out)
}
#' laplacian kernels
#'
#' @keywords internal
laplacian_kernels = function(type = 1) {
if (type == 1) {
out = matrix(c(1,1,1,1,-8,1,1,1,1), 3, 3)}
else if (type == 2) {
out = matrix(c(-1,2,-1,2,-4,2,-1,2,-1), 3, 3)}
else if (type == 3) {
out = matrix(c(0,1,0,1,-4,1,0,1,0), 3, 3)
}
else if (type == 4) {
out = matrix(c(-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1), 5, 5)
}
else {
stop('invalid type for laplacian mask')
}
return(out)
}
#' secondary function for edge_detection function
#'
#' @keywords internal
switch_filter = function(kernel, conv_mod, gaussian_dims = 5, sigma = 1.0, laplacian_type = 1, range_gauss = 2) {
kernel <- match.arg(kernel, c('Sobel', 'Prewitt', 'Roberts_cross', 'Frei_chen', 'Scharr', 'LoG'), FALSE)
if (kernel == 'LoG') { # a discrete kernel approximation for laplacian of Gaussian for a sigma of 1.4, http://homepages.inf.ed.ac.uk/rbf/HIPR2/log.htm
gaus_kern = norm_matrix_range(gaussian_kernel(gaussian_dims, sigma, range_gauss = 2), 0.0, 255.0) # pixels between 0 and 255 (by default)
lapl_kern = laplacian_kernels(laplacian_type)
convl = conv2d(gaus_kern, lapl_kern, mode = conv_mod)
return(convl/255.0)
}
else {
switch(kernel,
Sobel = {
G_horiz = matrix(c(-1, 0, 1, -2, 0, 2, -1, 0, 1), 3, 3);
G_vert = t(matrix(c(-1, 0, 1, -2, 0, 2, -1, 0, 1), 3, 3))},
Prewitt = {
G_horiz = matrix(c(-1, -1, -1, 0, 0, 0, 1, 1, 1), 3, 3);
G_vert = t(matrix(c(-1, -1, -1, 0, 0, 0, 1, 1, 1), 3, 3))},
Roberts_cross = {
G_horiz = matrix(c(1, 0, 0, -1), 2, 2);
G_vert = matrix(c(0, -1, 1, 0), 2, 2)},
Frei_chen = {
G_horiz = matrix(c(1, sqrt(2), 1, 0, 0, 0, -1, -sqrt(2), -1), 3, 3);
G_vert = t(matrix(c(-1, -sqrt(2), -1, 0, 0, 0, 1, sqrt(2), 1), 3, 3))},
Scharr = {
G_horiz = t(matrix(c(3, 10, 3, 0, 0, 0, -3, -10, -3), 3, 3));
G_vert = matrix(c(3, 10, 3, 0, 0, 0, -3, -10, -3), 3, 3)}
)
return(list(G_horiz = G_horiz, G_vert = G_vert))
}
}
#' function to check the range of values of an image or normalize an image
#'
#' @keywords internal
func_chech_range = function(image) {
if (inherits(image, 'matrix')) {
if ((max(image) != 1.0 || min(image) != 0.0)) {
image = Normalize_matrix(image)
}
} else if (inherits(image, 'array') && dim(image)[3] == 3) {
if (max(Array_range(image, 1)) != 1.0 || min(Array_range(image, 2)) != 0.0) {
image = Normalize_array(image)
}
} else {
return(image)
}
return(image)
}
#' edge detection (Frei_chen, LoG, Prewitt, Roberts_cross, Scharr, Sobel)
#'
#' @param image matrix or 3-dimensional array and the third dimension must be equal to 3
#' @param method the method should be one of 'Frei_chen', 'LoG' (Laplacian of Gaussian), 'Prewitt', 'Roberts_cross', 'Scharr', 'Sobel'
#' @param conv_mode the convolution mode should be one of 'same', 'full'
#' @param approx if TRUE, approximate calculation of gradient (applies to all filters except for 'LoG')
#' @param gaussian_dims integer specifying the horizontal and vertical dimensions of the gaussian filter
#' @param sigma float parameter sigma for the gaussian filter
#' @param range_gauss float number specifying the range of values for the gaussian filter
#' @param laplacian_type integer value specifying the type for the laplacian kernel (one of 1, 2, 3, 4)
#' @return depending on the input, either a matrix or an array
#' @author Lampros Mouselimis
#' @details
#' This function takes either a matrix or a 3-dimensional array (where the third dimension is equal to 3) and it performs edge detection using one of the following filters : 'Frei_chen', 'LoG' (Laplacian of Gaussian),
#' 'Prewitt', 'Roberts_cross', 'Scharr', 'Sobel'
#' @export
#' @examples
#'
#' path = system.file("tmp_images", "1.png", package = "OpenImageR")
#'
#' image = readImage(path)
#'
#' res = edge_detection(image, method = 'Frei_chen', conv_mode = 'same')
#'
edge_detection = function(image, method = NULL, conv_mode = 'same', approx = F, gaussian_dims = 5, sigma = 1.0, range_gauss = 2, laplacian_type = 1) {
if (is.null(method) || !method %in% c('Frei_chen', 'LoG', 'Prewitt', 'Roberts_cross', 'Scharr', 'Sobel')) stop("method shoud be non-NULL and one of : 'Frei_chen', 'LoG', 'Prewitt', 'Roberts_cross', 'Scharr', 'Sobel'")
if (inherits(image, 'data.frame')) image = as.matrix(image) # default conversion for armadillo function conv2d
if (is.null(conv_mode)) stop("conv_mode should be one of : 'full', 'same'")
if (!conv_mode %in% c('full', 'same')) stop("conv_mode should be one of : 'full', 'same'")
if (!approx %in% c(T, F)) stop("the 'approx' argument should be a boolean")
res_kernel = switch_filter(method, conv_mode, gaussian_dims = gaussian_dims, sigma = sigma, laplacian_type = laplacian_type, range_gauss = range_gauss)
if (inherits(res_kernel, 'list')) {
if (inherits(image, 'array') && !is.na(dim(image)[3]) && dim(image)[3] == 3) {
new_image_horizontal = conv3d(image, res_kernel$G_horiz, conv_mode)
new_image_vertical = conv3d(image, res_kernel$G_vert, conv_mode)
}
else if (inherits(image, 'matrix')) {
new_image_horizontal = conv2d(image, res_kernel$G_horiz, conv_mode)
new_image_vertical = conv2d(image, res_kernel$G_vert, conv_mode)
}
else {
stop("the 'image' parameter can be either a matrix or a 3-dimensional array where the third dimension is equal to 3")
}
if (approx) {
res = abs(new_image_horizontal) + abs(new_image_vertical)} # an approximate calculation is much faster, http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.301.927&rep=rep1&type=pdf
else {
res = sqrt((new_image_horizontal) ^ 2 + (new_image_vertical) ^ 2)
}
res = func_chech_range(res)
return(res)
}
else if (inherits(res_kernel, 'matrix')) {
if (is.array(image) && !is.na(dim(image)[3]) && dim(image)[3] == 3) {
new_LoG = conv3d(image, res_kernel, conv_mode)
}
else if (is.matrix(image)) {
new_LoG = conv2d(image, res_kernel, mode = conv_mode)
}
else {
stop("the 'new_LoG' parameter can be either a matrix or a 3-dimensional array where the third dimension is equal to 3")
}
new_LoG = func_chech_range(new_LoG)
return(new_LoG)
}
else {
stop('invalid kernel object')
}
}
#' uniform filter (convolution with uniform kernel)
#'
#' @param image matrix or 3-dimensional array where the third dimension is equal to 3
#' @param size a 2-item vector specifying the horizontal and vertical dimensions of the uniform kernel, e.g. c(3,3)
#' @param conv_mode the convolution mode should be one of 'same', 'full'
#' @return depending on the input, either a matrix or an array
#' @author Lampros Mouselimis
#' @details
#' This function applies a uniform filter to a matrix or to a 3-dimensional array where the third dimension is equal to 3
#' @export
#' @examples
#'
#' path = system.file("tmp_images", "1.png", package = "OpenImageR")
#'
#' image = readImage(path)
#'
#' filt = uniform_filter(image, c(4,4), conv_mode = "same")
#'
uniform_filter = function(image, size, conv_mode = 'same') {
if (!is.vector(size)) stop('The size argument must be a vector specifying the dimensions of the uniform filter such as c(3,3)')
if (is.null(conv_mode)) stop("conv_mode should be one of : 'full', 'same'")
if (!conv_mode %in% c('full', 'same')) stop("conv_mode should be one of : 'full', 'same'")
unif_filt = matrix(1, ncol = size[1], nrow = size[2])/(size[1] * size[2])
if (all(c(inherits(image, 'array'), !is.na(dim(image)[3]), dim(image)[3] == 3))) {
out = conv3d(image, unif_filt, conv_mode)
}
else if (is.matrix(image)) {
out = conv2d(image, unif_filt, conv_mode)
}
else {
stop('valid type of input-images is array or matrix')
}
return(out)
}
#' image thresholding
#'
#' @param image matrix or 3-dimensional array where the third dimension is equal to 3
#' @param thresh the threshold parameter should be between 0 and 1 if the data is normalized or between 0-255 otherwise
#' @return a matrix
#' @author Lampros Mouselimis
#' @details
#' This function applies thresholding to a matrix or to a 3-dimensional array where the third dimension is equal to 3.
#' @export
#' @examples
#'
#' path = system.file("tmp_images", "1.png", package = "OpenImageR")
#'
#' image = readImage(path)
#'
#' filt = image_thresholding(image, thresh = 0.5)
#'
image_thresholding = function(image, thresh) {
if (thresh <= 0.0) stop('the thresh parameter should be greater than 0')
if (inherits(image, 'data.frame')) image = as.matrix(image)
if (inherits(image, 'matrix')) {
image_out = ifelse(image > thresh, 1, 0)
}
else if (all(c(inherits(image, 'array'), !is.na(dim(image)[3]), dim(image)[3] == 3))) {
image = rgb_2gray(image)
image_out = ifelse(image > thresh, 1, 0)
}
else {
stop('the image should be either a matrix or a 3-dimensional array where the third dimension is equal to 3')
}
return(image_out)
}
#' Gamma correction
#'
#' @param image matrix or 3-dimensional array where the third dimension is equal to 3
#' @param gamma a positive value
#' @return depending on the input, either a matrix or an array
#' @author Lampros Mouselimis
#' @details
#' This function applies gamma correction to a matrix or to a 3-dimensional array where the third dimension is equal to 3. The gamma correction controls the overall brightness of an image.
#' @export
#' @examples
#'
#' path = system.file("tmp_images", "2.jpg", package = "OpenImageR")
#'
#' image = readImage(path)
#'
#' filt = gamma_correction(image, gamma = 0.5)
#'
gamma_correction = function(image, gamma) {
if (inherits(image, 'array') || inherits(image, 'matrix')) {
out = ((image ) ^ (1 / gamma))
}
else {
stop('the image should be either a matrix or an array')
}
return(out)
}
#' secondary function for downsampling
#'
#' @keywords internal
sec_gaus_bl = function(image, factor, sigma, range_gauss) {
kernel_size = ifelse(factor == 2, 3, round( 3 * (factor / 2)))
gaus_kern = gaussian_kernel(kernel_size, sigma = sigma, range_gauss = range_gauss)
image = conv2d(image, gaus_kern, 'same') # convolve
return(image)
}
#' downsampling an image ( by a factor ) using gaussian blur
#'
#' @param image matrix or 3-dimensional array where the third dimension is equal to 3
#' @param factor a positive number greater or equal to 1.0
#' @param gaussian_blur a boolean (TRUE,FALSE) specifying if gaussian blur should be applied when downsampling
#' @param gauss_sigma float parameter sigma for the gaussian filter
#' @param range_gauss float number specifying the range of values for the gaussian filter
#' @return depending on the input, either a matrix or an array
#' @author Lampros Mouselimis
#' @details
#' This function downsamples an image with the option to use gaussian blur for optimal output.
#' @export
#' @examples
#'
#' path = system.file("tmp_images", "2.jpg", package = "OpenImageR")
#'
#' image = readImage(path)
#'
#' dsamp = down_sample_image(image, factor = 2.0, gaussian_blur = TRUE)
#'
down_sample_image = function(image, factor, gaussian_blur = FALSE, gauss_sigma = 1.0, range_gauss = 2) {
if (!is.logical(gaussian_blur)) stop("'gaussian_blur should be one of TRUE, FALSE")
if (inherits(image, 'data.frame')) image = as.matrix(image)
if (!inherits(image, c('matrix', 'array'))) stop('invalid type of image, use either array or matrix')
if (factor < 1.0) stop('factor should be greater or equal to 1.0')
new_rows = seq(1, nrow(image), factor)
new_cols = seq(1, ncol(image), factor)
if (gaussian_blur) { # use a gaussian kernel to perform gaussian blurring
if (is.array(image) && !is.na(dim(image)[3]) && dim(image)[3] == 3) {
new_array = list()
for (i in 1:dim(image)[3]) {
new_array[[i]] = sec_gaus_bl(matrix(image[,,i], dim(image)[1], dim(image)[2]), factor, gauss_sigma, range_gauss)
}
new_array = array(unlist(new_array), dim = c(nrow(new_array[[1]]), ncol(new_array[[1]]), length(new_array)))
out = new_array[new_rows, new_cols, ]
}
if (is.matrix(image)) {
new_array = sec_gaus_bl(image, factor, gauss_sigma, range_gauss)
out = new_array[new_rows, new_cols]
}
}
else {
if (inherits(image, 'matrix')) {
out = image[new_rows, new_cols]
}
else if (inherits(image, 'array')) {
out = image[new_rows, new_cols, ]
}
else {
stop('invalid type of image, use either array or matrix')
}
}
return(out)
}
#' crop an image in R [ for RGB or grey images ]
#'
#' @keywords internal
crop_image_secondary = function(image, new_width, new_height) { # reduce image size for 'equal_spaced'
r = nrow(image)
c = ncol(image)
if (new_width > r) stop("The 'new_width' parameter should be less than or equal to the input rows of the image", call. = F)
if (new_height > c) stop("The 'new_height' parameter should be less than or equal to the input columns of the image", call. = F)
if (new_width != r) {
dif_rows = r - new_width
rem_rows = dif_rows %% 2
keep_rows = (floor(dif_rows/2) + 1):(r - floor(dif_rows/2) - rem_rows)
}
else {
keep_rows = 1:r
}
if (new_height != c) {
dif_cols = c - new_height
rem_cols = dif_cols %% 2
keep_cols = (floor(dif_cols/2) + 1):(c - floor(dif_cols/2) - rem_cols)
}
else {
keep_cols = 1:c
}
return(image[keep_rows, keep_cols])
}
#' crop an image
#'
#' @param image matrix or 3-dimensional array where the third dimension is equal to 3
#' @param new_width Corresponds to the image-rows. If 'equal_spaced' then the new_width should be numeric of length 1. If 'user_defined' then the new_width should be a sequence of numeric values.
#' @param new_height Corresponds to the image-columns. If 'equal_spaced' then the new_height should be numeric of length 1. If 'user_defined' then the new_height should be a sequence of numeric values.
#' @param type a string specifying the type ('equal_spaced' or 'user_defined'). If 'equal_spaced' the image will be cropped towards the center (equal distances horizontaly and verticaly). If 'user_defined' the user specifies the cropped region.
#' @return depending on the input, either a matrix or an array
#' @author Lampros Mouselimis
#' @details
#' This function crops an image in two different ways.
#' @export
#' @examples
#'
#' path = system.file("tmp_images", "2.jpg", package = "OpenImageR")
#'
#' image = readImage(path)
#'
#' # IF 'equal_spaced':
#' crop1 = cropImage(image, new_width = 20, new_height = 20, type = 'equal_spaced')
#'
#' # IF 'user_defined':
#' crop2 = cropImage(image, new_width = 5:20, new_height = 5:20, type = 'user_defined')
#'
cropImage = function(image, new_width, new_height, type = 'equal_spaced') {
if (is.null(new_width) || is.null(new_height) || !inherits(new_height, c('numeric', 'integer')) || !inherits(new_width, c('numeric', 'integer'))) stop('new_height and new_width should be of type numeric')
if (!type %in% c('equal_spaced', 'user_defined') || is.null(type)) stop('valid types are equal_spaced and user_defined')
if (type == 'equal_spaced' && (length(new_height) != 1 || length(new_width) != 1)) stop('if the type is equal_spaced then the new_height and new_width should be numeric of length 1')
if (type == 'user_defined' && (length(new_height) < 2 || length(new_width) < 2)) stop('if the type is user_defined then the new_height and new_width should be a sequence of numeric values')
if (type == 'equal_spaced') {
if (inherits(image, 'matrix')) {
res = crop_image_secondary(image, new_width, new_height)
}
else if (all(c(inherits(image, 'array'), !is.na(dim(image)[3]), dim(image)[3] == 3))) {
res = array(, dim = c(new_width, new_height, dim(image)[3]))
for (i in 1:dim(image)[3]) {
res[,, i] = crop_image_secondary(image[,, i], new_width, new_height)
}
}
else {
stop('invalid type of image, supported types are matrix and 3 dimensional array')
}
}
if (type == 'user_defined') {
if (inherits(image, 'matrix')) {
res = image[new_width, new_height]
}
else if (all(c(inherits(image, 'array'), !is.na(dim(image)[3]), dim(image)[3] == 3))) {
res = array(, dim = c(length(new_width), length(new_height), dim(image)[3]))
for (i in 1:dim(image)[3]) {
res[,, i] = image[new_width, new_height, i]
}
}
else {
stop('invalid type of image, supported types are matrix and 3 dimensional array')
}
}
return(res)
}
#' Rotate an image using the 'nearest' or 'bilinear' method
#'
#'
#' Rotate an image by angle using the 'nearest' or 'bilinear' method
#'
#' @param image matrix, data frame or 3-dimensional array where the third dimension is equal to 3
#' @param angle specifies the number of degrees
#' @param method a string specifying the interpolation method when rotating an image ( 'nearest', 'bilinear' )
#' @param mode one of 'full', 'same' (same indicates that the ouput image will have the same dimensions with initial image)
#' @param threads the number of cores to run in parallel
#' @return depending on the input, either a matrix or an array
#' @details
#' This function rotates an image by a user-specified angle
#' @export
#' @examples
#'
#' path = system.file("tmp_images", "2.jpg", package = "OpenImageR")
#'
#' image = readImage(path)
#'
#' r = rotateImage(image, 75, threads = 1)
#'
rotateImage = function(image, angle, method = 'nearest', mode = 'same', threads = 1) {
if (threads < 1) stop('threads should be greater than 0')
if (angle > 360.0 || angle < 0.0) stop("valid angles to rotate an image are values greater than 0 and less than 360")
if (!method %in% c('nearest', 'bilinear')) stop("valid methods are 'nearest', 'bilinear'")
if (!mode %in% c('same', 'full')) stop("invalid mode, choose one of 'same', 'full'")
if (inherits(image, 'data.frame')) image = as.matrix(image)
if (inherits(image, 'matrix')) {
out = rotate_nearest_bilinear(image, angle, method, mode, threads)
}
else if (inherits(image, 'array') && !is.na(dim(image)[3]) && dim(image)[3] == 3) {
if (mode == 'same') {
out = rotate_nearest_bilinear_array_same(image, angle, method, threads)
}
if (mode == 'full') {
out = rotate_nearest_bilinear_array_full(image, angle, method, threads)
}
}
else {
stop('invalid type of image, supported types are matrix, data frame and 3 dimensional array')
}
return(out)
}
#' Rotate an image by 90, 180, 270 degrees
#'
#' @param image matrix, data frame or 3-dimensional array where the third dimension is equal to 3
#' @param angle one of 90, 180 and 270 degrees
#' @return depending on the input, either a matrix or an array
#' @details
#' This function is faster than the rotateImage function as it rotates an image for specific angles (90, 180 or 270 degrees).
#' @export
#' @examples
#'
#' path = system.file("tmp_images", "3.jpeg", package = "OpenImageR")
#'
#' image = readImage(path)
#'
#' r = rotateFixed(image, 90)
#'
rotateFixed = function(image, angle) {
if (inherits(image, 'data.frame')) image = as.matrix(image)
if (inherits(image, 'matrix')) {
out = rotate_rcpp(image, angle)}
else if (all(c(inherits(image, 'array'), !is.na(dim(image)[3]), dim(image)[3] == 3))) {
new_array = list()
for (i in 1:dim(image)[3]) {
new_array[[i]] = rotate_rcpp(matrix(image[,,i], dim(image)[1], dim(image)[2]), angle)
}
out = array(unlist(new_array), dim = c(nrow(new_array[[1]]), ncol(new_array[[1]]), length(new_array)))
}
else {
stop('invalid type of image, supported types are matrix and 3 dimensional array')
}
return(out)
}
#' secondary function for 'resizeImage' [ array ]
#'
#' @keywords internal
sec_resiz_array = function(image, flag = T) {
if (flag) {
if (max(apply(image, 3, max)) <= 1.0) {
image = image * 255
}
}
else {
if (max(as.vector(image)) <= 1.0) {
image = image * 255
}
}
return(image)
}
#' resize an image using the 'nearest neighbors' or the 'bilinear' method
#'
#' @param image matrix or 3-dimensional array where the third dimension is equal to 3
#' @param width a number specifying the new width of the image. Corresponds to the image-rows.
#' @param height a number specifying the new height of the image. Corresponds to the image-columns.
#' @param method one of 'nearest', 'bilinear'
#' @param normalize_pixels a boolean. If TRUE, then the output pixel values will be divided by 255.0
#' @return depending on the input, either a matrix or an array
#' @author Lampros Mouselimis
#' @details
#' This function down- or upsamples an image using the 'nearest neighbors' or the 'bilinear' method
#' @export
#' @examples
#'
#' path = system.file("tmp_images", "2.jpg", package = "OpenImageR")
#'
#' image = readImage(path)
#'
#' resiz = resizeImage(image, width = 32, height = 32, method = 'nearest')
#'
resizeImage = function(image, width, height, method = 'nearest', normalize_pixels = FALSE) {
if (inherits(image, 'data.frame')) image = as.matrix(image)
if (width < 1.0) stop("width should be at least 1.0")
if (height < 1.0) stop("height should be at least 1.0")
if (!method %in% c('nearest', 'bilinear')) stop("valid methods are 'nearest' or 'bilinear'")
if (all(c(inherits(image, 'array'), !is.na(dim(image)[3]), dim(image)[3] == 3))) {
image = sec_resiz_array(image, T)
if (method == 'nearest') {
out = resize_nearest_array(image, width, height)
}
if (method == 'bilinear') {
out = bilinear_array(image, width, height)
}
}
else if (inherits(image, 'matrix')) {
image = sec_resiz_array(image, F)
if (method == 'nearest') {
out = resize_nearest_rcpp(image, width, height)
}
if (method == 'bilinear') {
out = resize_bilinear_rcpp(image, width, height)
}
}
else {
stop('invalid type of image, use either a matrix, data frame or array')
}
if (normalize_pixels) out = out / 255.0
return(out)
}
#' flip image horizontally or vertically
#'
#' flip an image row-wise (horizontally) or column-wise (vertically)
#'
#' @param image a matrix, data frame or 3-dimensional array where the third dimension is equal to 3
#' @param mode one of 'horizontal', 'vertical'
#' @return a matrix or 3-dimensional array where the third dimension is equal to 3
#' @details
#' This function flips an image row-wise or column-wise
#' @export
#' @examples
#'
#' path = system.file("tmp_images", "1.png", package = "OpenImageR")
#'
#' im = readImage(path)
#'
#' flp = flipImage(im, mode = 'vertical')
#'
flipImage = function(image, mode = 'horizontal') {
if (mode == 'vertical') {
mode = 1}
else if (mode == 'horizontal') {
mode = 2}
else {
stop('invalid mode')
}
if (inherits(image, 'data.frame')) image = as.matrix(image)
if (inherits(image, 'matrix')) {
res = im_flip(image, mode)
}
else if (all(c(inherits(image, 'array'), !is.na(dim(image)[3]), dim(image)[3] == 3))) {
res = im_flip_cube(image, mode)
}
else {
stop('valid types of input are matrix, data frame and 3-dimensional array where the third dimension is equal to 3')
}
return(res)
}
#' zca whiten of an image
#'
#'
#' this function performs zca-whitening to a 2- or 3- dimensional image
#' @param image a matrix, data frame or 3-dimensional array where the third dimension is equal to 3
#' @param k an integer specifying the number of components to keep when svd is performed (reduced dimension representation of the data)
#' @param epsilon a float specifying the regularization parameter
#' @return a matrix or 3-dimensional array where the third dimension is equal to 3
#' @details
#' Whitening (or sphering) is the preprocessing needed for some algorithms. If we are training on images, the raw input is redundant, since adjacent
#' pixel values are highly correlated. When using whitening the features become less correlated and all features have the same variance.
#' @references
#' http://ufldl.stanford.edu/wiki/index.php/Whitening
#' @export
#' @examples
#'
#' path = system.file("tmp_images", "1.png", package = "OpenImageR")
#'
#' image = readImage(path)
#'
#' res = ZCAwhiten(image, k = 20, epsilon = 0.1)
#'
ZCAwhiten = function(image, k, epsilon) {
if (epsilon <= 0) stop('epsilon should be greater than 0')
if (inherits(image, 'data.frame')) image = as.matrix(image)
if (inherits(image, 'matrix')) {
if (k < 1 || k > ncol(image)) stop('k should be greater or equal to 1 and less than ncol(image) + 1')
res = zca_whitening(image, k, epsilon)
}
else if (all(c(inherits(image, 'array'), !is.na(dim(image)[3]), dim(image)[3] == 3))) {
if (k < 1 || k > ncol(image[,,1])) stop('k should be greater or equal to 1 and less than ncol(image) + 1 of each array slice')
res = zca_whiten_cube(image, k, epsilon)
}
else {
stop('valid types of input are matrix, data frame and 3-dimensional array where the third dimension is equal to 3')
}
return(res)
}
#' Delation or Erosion of an image
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' This function was deprecated because I realized that the name of the function does not correspond to the name of the algorithm (delation -> dilation)
#'
#' this function performs delation or erosion to a 2- or 3- dimensional image
#' @param image a matrix, data frame or 3-dimensional array where the third dimension is equal to 3
#' @param Filter a vector specifying the dimensions of the kernel, which will be used to perform either delation or erosion, such as c(3,3)
#' @param method one of 'delation', 'erosion'
#' @param threads number of cores to run in parallel ( > 1 should be used if image high dimensional )
#' @return a matrix or 3-dimensional array where the third dimension is equal to 3
#' @details
#' This function utilizes a kernel to perform delation or erosion. The first value of the vector indicates the number of rows of the kernel, whereas
#' the second value indicates the number of columns.
#' @keywords internal
#' @export
#' @examples
#'
#' path = system.file("tmp_images", "1.png", package = "OpenImageR")
#'
#' image = readImage(path)
#'
#' res_delate = delationErosion(image, Filter = c(3,3), method = 'delation')
#'
#' res_erode = delationErosion(image, Filter = c(5,5), method = 'erosion')
#'
#' # ->
#'
#' res_dilate = dilationErosion(image, Filter = c(3,3), method = 'dilation')
#'
#' res_erode = dilationErosion(image, Filter = c(5,5), method = 'erosion')
#'
delationErosion = function(image, Filter, method = 'delation', threads = 1) {
lifecycle::deprecate_warn("1.2.5", "delationErosion()", "dilationErosion()")
if (inherits(image, 'data.frame')) image = as.matrix(image)
if (!inherits(image, c('matrix', 'array'))) stop('invalid type of image, use either array or matrix')
if (threads < 1) stop('theads should be at least 1')
if (!method %in% c('delation', 'erosion')) stop("invalid method, choose one of 'delation', 'erosion'")
if (length(Filter) != 2 || Filter[1] < 1 || Filter[2] < 1 || Filter[1] > nrow(image) - 1 || Filter[2] > ncol(image) - 1 || (!inherits(Filter, 'numeric')))
stop('Filter should be a numeric vector, such as c(3,3), where each value of the vector is greater than 1 and less than the number of
rows and columns of the image')
if (method == 'delation') {
method = 1}
if (method == 'erosion') {
method = 2
}
if (inherits(image, 'matrix')) {
res = diate_erode(image, Filter, method, threads)
}
if (all(c(inherits(image, 'array'), !is.na(dim(image)[3]), dim(image)[3] == 3))) {
res = diate_erode_cube(image, Filter, method, threads)
}
return(res)
}
#' Dilation or Erosion of an image
#'
#' this function performs dilation or erosion to a 2- or 3- dimensional image
#' @param image a matrix, data frame or 3-dimensional array where the third dimension is equal to 3
#' @param Filter a vector specifying the dimensions of the kernel, which will be used to perform either dilation or erosion, such as c(3,3)
#' @param method one of 'dilation', 'erosion'
#' @param threads number of cores to run in parallel ( > 1 should be used if image high dimensional )
#' @return a matrix or 3-dimensional array where the third dimension is equal to 3
#' @details
#' This function utilizes a kernel to perform dilation or erosion. The first value of the vector indicates the number of rows of the kernel, whereas
#' the second value indicates the number of columns.
#' @export
#' @examples
#'
#' path = system.file("tmp_images", "1.png", package = "OpenImageR")
#'
#' image = readImage(path)
#'
#' res_dilate = dilationErosion(image, Filter = c(3,3), method = 'dilation')
#'
#' res_erode = dilationErosion(image, Filter = c(5,5), method = 'erosion')
#'
dilationErosion = function(image, Filter, method = 'dilation', threads = 1) {
if (inherits(image, 'data.frame')) image = as.matrix(image)
if (!inherits(image, c('matrix', 'array'))) stop('invalid type of image, use either array or matrix')
if (threads < 1) stop('theads should be at least 1')
if (!method %in% c('dilation', 'erosion')) stop("invalid method, choose one of 'dilation', 'erosion'")
if (length(Filter) != 2 || Filter[1] < 1 || Filter[2] < 1 || Filter[1] > nrow(image) - 1 || Filter[2] > ncol(image) - 1 || (!inherits(Filter, 'numeric')))
stop('Filter should be a numeric vector, such as c(3,3), where each value of the vector is greater than 1 and less than the number of
rows and columns of the image')
if (method == 'dilation') {
method = 1}
if (method == 'erosion') {
method = 2
}