-
Notifications
You must be signed in to change notification settings - Fork 4
/
staticTransforms.py
2192 lines (1823 loc) · 80.9 KB
/
staticTransforms.py
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
import os
import json
import random
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import pprint as pp
import numpy as np
import matplotlib.pyplot as plt
import cv2
import PIL
from PIL import Image, ImageDraw
import torch
from torchvision import transforms
import albumentations as A
from functools import wraps
# Functools module is for higher-order functions that work on other functions.
# It provides functions for working with other functions and callable objects to use or extend them without completely rewriting them.
# ### Dependencies
#
# #### All dependencies are in requirements.txt
#
# (Use this command to generate the requirement.txt
# **conda list -e > requirements.txt**)
#
# Install albumentations using the following commands
# * pip install -U albumentations
# * pip install -U git+https://github.com/albumentations-team/albumentations
#
# Why albumentations?
# https://docs.google.com/spreadsheets/d/1rmaGngJXj3X0_ugVLWVW7h4lvayWiIJO_o2dfRNQ380/edit?usp=sharing
# ### Transform Functions
# * Blur
# * CLAHE
# * ChannelDropout
# * ChannelShuffle
# * ColorJitter
# * Downscale
# * Emboss
# * FancyPCA
# * FromFloat (Not used while evaluating model accuracies)
# * GaussNoise
# * GaussianBlur
# * GlassBlur
# * HueSaturationValue
# * ISONoise
# * InvertImg
# * MedianBlur
# * MotionBlur
# * MultiplicativeNoise
# * Normalize (Not used while evaluating model accuracies)
# * Posterize
# * RGBShift
# * Sharpen
# * Solarize
# * Superpixels
# * ToFloat (Not used while evaluating model accuracies)
# * ToGray
# * ToSepia
# * VerticalFlip
# * HorizontalFlip
# * Flip (Not used while evaluating model accuracies)
# * Transpose
# * OpticalDistortion
# * GridDistortion
# * JpegCompression
# * Cutout
# * CoarseDropout
# * MaskDropout (Not used while evaluating model accuracies)
# * GridDropout
# * FDA (Non-Functional)
# * Equalize (Non-Functional)
# * HistogramMatching (Non-Functional)
# * ImageCompression (Non-Functional)
# * PixelDistributionAdaptation (Non-Functional)
# * PadIfNeeded (Non-Functional)
# * Lambda (Non-Functional)
# * TemplateTransform (Non-Functional)
# * RingingOvershoot (Non-Functional)
# * UnsharpMask (Non-Functional)
# Blur
def Blur(image, blur_limit=(3, 7), always_apply=False, p=1.0):
"""
Blur the input image using a random-sized kernel.
Args:
image (numpy.ndarray): Input image to be blurred.
blur_limit (tuple or int): Maximum kernel size for blurring the input image.
Should be in range [3, inf). Default: (3, 7).
always_apply (bool): Whether to always apply the transform. Default: False.
p (float): Probability of applying the transform. Default: 1.0.
Returns:
numpy.ndarray: Blurred image.
Targets:
image
Image types:
uint8, float32
"""
transform = A.Compose([A.augmentations.transforms.Blur(blur_limit, always_apply, p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# CLAHE ( Contrast Limited Adaptive Histogram Equalization )
def CLAHE(image, clip_limit=(1, 4), tile_grid_size=(8, 8), always_apply=False, p=1.0):
"""
Apply Contrast Limited Adaptive Histogram Equalization to the input image.
Args:
image (numpy.ndarray): Input image to be processed.
clip_limit (float or tuple of float): Upper threshold value for contrast limiting.
If clip_limit is a single float value, the range will be (1, clip_limit). Default: (1, 4).
tile_grid_size (tuple of int): Size of grid for histogram equalization. Default: (8, 8).
always_apply (bool): Whether to always apply the transform. Default: False.
p (float): Probability of applying the transform. Default: 1.0.
Returns:
numpy.ndarray: Processed image.
Targets:
image
Image types:
uint8
"""
transform = A.Compose([A.augmentations.transforms.CLAHE(clip_limit, tile_grid_size, always_apply, p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# ChannelDropout
def ChannelDropout(image,channel_drop_range=(1, 1), fill_value=0, always_apply=False, p=1.0):
"""
Randomly drop channels in the input image.
Args:
image (numpy.ndarray): Input image to randomly drop channels.
channel_drop_range (tuple of int): Range from which we choose the number of channels to drop. Default: (1, 1).
fill_value (int or float): Pixel value for the dropped channel. Default: 0.
always_apply (bool): Whether to always apply the transform. Default: False.
p (float): Probability of applying the transform. Default: 1.0.
Returns:
numpy.ndarray: Image with randomly dropped channels.
Targets:
image
Image types:
uint8, uint16, uint32, float32
"""
transform = A.Compose([A.augmentations.ChannelDropout(channel_drop_range, fill_value, always_apply, p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# ChannelShuffle
def ChannelShuffle(image, p=1.0):
"""
Randomly rearrange channels of the input RGB image.
Args:
p (float): Probability of applying the transform. Default: 1.0.
Returns:
numpy.ndarray: Image with shuffled channels.
Targets:
image
Image types:
uint8, float32
"""
transform = A.Compose([A.augmentations.transforms.ChannelShuffle(p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# ColorJitter
def ColorJitter (image,brightness=0.2, contrast=0.2, saturation=0.2, hue=0.2, always_apply=False, p=1.0):
"""
Randomly changes the brightness, contrast, and saturation of an image. Compared to ColorJitter from torchvision,
this transform gives a little bit different results because Pillow (used in torchvision) and OpenCV (used in
Albumentations) transform an image to HSV format by different formulas. Another difference - Pillow uses uint8
overflow, but we use value saturation.
Args:
image (numpy.ndarray): The image to be transformed.
brightness (float or tuple of float (min, max)): How much to jitter brightness.
brightness_factor is chosen uniformly from [max(0, 1 - brightness), 1 + brightness]
or the given [min, max]. Should be non negative numbers.
contrast (float or tuple of float (min, max)): How much to jitter contrast.
contrast_factor is chosen uniformly from [max(0, 1 - contrast), 1 + contrast]
or the given [min, max]. Should be non negative numbers.
saturation (float or tuple of float (min, max)): How much to jitter saturation.
saturation_factor is chosen uniformly from [max(0, 1 - saturation), 1 + saturation]
or the given [min, max]. Should be non negative numbers.
hue (float or tuple of float (min, max)): How much to jitter hue.
hue_factor is chosen uniformly from [-hue, hue] or the given [min, max].
Should have 0 <= hue <= 0.5 or -0.5 <= min <= max <= 0.5.
always_apply (bool): Whether to always apply the transform.
p (float): The probability of applying the transform.
Returns:
numpy.ndarray: The transformed image.
"""
transform = A.Compose([A.ColorJitter(brightness=brightness, contrast=contrast, saturation=saturation, hue=hue, always_apply=always_apply, p=p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# Downscale
def Downscale (image,scale_min=0.25, scale_max=0.25, interpolation=0, always_apply=False, p=1.0):
"""
Decreases image quality by downscaling and upscaling back.
Args:
image (numpy.ndarray): The image to be downscaled and upscaled back.
scale_min (float): The lower bound on the image scale. Should be less than 1.
scale_max (float): The upper bound on the image scale. Should be less than 1.
interpolation (int): The cv2 interpolation method. cv2.INTER_NEAREST by default.
always_apply (bool): Whether to always apply the transform.
p (float): The probability of applying the transform.
Targets:
image
Image types:
numpy.ndarray of type uint8 or float32.
Returns:
numpy.ndarray: The transformed image.
"""
transform = A.Compose([A.augmentations.transforms.Downscale(scale_min=scale_min, scale_max=scale_max, interpolation=interpolation, always_apply=always_apply, p=p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# Emboss
def Emboss (image,alpha=(0.2, 0.5), strength=(0.2, 0.7), always_apply=False, p=1.0):
"""Emboss the input image and overlays the result with the original image.
Args:
alpha ((float, float)): range to choose the visibility of the embossed image. At 0, only the original image is
visible,at 1.0 only its embossed version is visible. Default: (0.2, 0.5).
strength ((float, float)): strength range of the embossing. Default: (0.2, 0.7).
p (float): probability of applying the transform. Default: 1.0.
Targets:
image
"""
transform = A.Compose([A.augmentations.transforms.Emboss (alpha, strength, always_apply, p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# Equalize
"""
Embosses the input image and overlays the result with the original image.
Args:
image (numpy.ndarray): The input image to be embossed.
alpha (tuple of float): The range to choose the visibility of the embossed image. At 0, only the original image is
visible; at 1.0 only its embossed version is visible. Default: (0.2, 0.5).
strength (tuple of float): The strength range of the embossing. Default: (0.2, 0.7).
always_apply (bool): Whether to always apply the transform.
p (float): The probability of applying the transform.
Targets:
image
Returns:
numpy.ndarray: The transformed image.
transform = A.Compose([A.augmentations.transforms.Emboss(alpha=alpha, strength=strength, always_apply=always_apply, p=p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
"""
# FDA (Fourier Domain Adaptation
"""
def FDA (image, reference_images, beta_limit=0.1, read_fn='', always_apply=False, p=1.0):
Apply Contrast Limited Adaptive Histogram Equalization to the input image.
Args:
image (numpy.ndarray): Input image to be transformed.
reference_images (numpy.ndarray): Reference images for the transformation.
beta_limit (float): Parameter to control contrast amplification. Default: 0.1.
read_fn (str): Path to the file containing reference images. Default: ''.
always_apply (bool): Whether to always apply the transformation. Default: False.
p (float): Probability of applying the transform. Default: 1.0.
Returns:
numpy.ndarray: The transformed image.
Targets:
image
Image types:
uint8
Refer:
https://github.com/YanchaoYang/FDA
transform = A.Compose([A.augmentations.FDAFDA (reference_images, beta_limit, read_fn, always_apply, p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
"""
# FancyPCA
def FancyPCA (image,alpha=0.1, always_apply=False, p=1.0):
"""Augment RGB image using FancyPCA from Krizhevsky's paper "ImageNet Classification with Deep Convolutional
Neural Networks".
Args:
image (ndarray): RGB image to be augmented.
alpha (float): Scale factor for perturbation of eigenvalues and eigenvectors. Scale is sampled from a
Gaussian distribution with mu=0 and sigma=alpha. Default is 0.1.
always_apply (bool): Indicates whether the transform should always be applied, regardless of the given
probability. Default is False.
p (float): Probability of applying the transform. Default is 1.0.
Returns:
ndarray: Augmented image.
Targets:
image
Image types:
3-channel uint8 images only
Credit:
- Krizhevsky, A., Sutskever, I., & Hinton, G. E. (2012). ImageNet classification with deep convolutional
neural networks. Advances in neural information processing systems, 25, 1097-1105.
- Deshanadesai.github.io. (2022). Fancy PCA with Scikit-Image. [online]
Available at: https://deshanadesai.github.io/notes/Fancy-PCA-with-Scikit-Image [Accessed 23 Apr. 2023].
- Pixelatedbrian.github.io. (2022). Fancy PCA. [online]
Available at: https://pixelatedbrian.github.io/2018-04-29-fancy_pca/ [Accessed 23 Apr. 2023].
"""
transform = A.Compose([A.augmentations.transforms.FancyPCA (alpha, always_apply, p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# FromFloat
def FromFloat (image,dtype='uint16', max_value=None, always_apply=False, p=1.0):
"""Converts input array where all values should lie in the range [0, 1.0] to values in the range [0, max_value] and
cast the resulted value to a type specified by `dtype`. If `max_value` is None the transform will try to infer
the maximum value for the data type from the `dtype` argument. This is the inverse transform for
`albumentations.augmentations.transforms.ToFloat`.
Args:
image: Input image.
max_value (float): Maximum possible input value. Default: None.
dtype (str or np.dtype): Data type of the output. Default: 'uint16'.
always_apply (bool): If True, apply the transform to all images, otherwise only apply to a random subset.
Default: False.
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image
Image types:
float32
Returns:
The transformed image.
"""
transform = A.Compose([A.augmentations.transforms.FromFloat(dtype=dtype, max_value=max_value,
always_apply=always_apply, p=p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# GaussNoise
def GaussNoise (image,var_limit=(10.0, 50.0), mean=0, per_channel=True, always_apply=False, p=1.0):
"""Apply Gaussian noise to the input image.
Args:
var_limit (float or tuple of floats): variance range for noise. If var_limit is a single float, the range
will be (0, var_limit). Default: (10.0, 50.0).
mean (float): mean of the noise. Default: 0
per_channel (bool): if set to True, noise will be sampled for each channel independently.
Otherwise, the noise will be sampled once for all channels. Default: True
always_apply (bool): apply the transform to every input. Default: False
p (float): probability of applying the transform. Default: 1.0.
Targets:
image
Image types:
uint8, float32
"""
transform = A.Compose([A.augmentations.transforms.GaussNoise(var_limit=var_limit, mean=mean, per_channel=per_channel,
always_apply=always_apply, p=p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# GaussianBlur
def GaussianBlur (image, blur_limit=(3, 7), sigma_limit=0, always_apply=False, p=1.0):
"""
Blur the input image using a Gaussian filter with a random kernel size.
Args:
image (numpy.ndarray): Input image to be blurred.
blur_limit (int or tuple(int, int)): Maximum Gaussian kernel size for blurring the input image.
Must be zero or odd and in range [0, inf). If set to 0 it will be computed from sigma
as `round(sigma * (3 if img.dtype == np.uint8 else 4) * 2 + 1) + 1`.
If set to a single value, `blur_limit` will be in range (0, blur_limit).
Default: (3, 7).
sigma_limit (float or tuple(float, float)): Gaussian kernel standard deviation. Must be greater in range [0, inf).
If set to a single value, `sigma_limit` will be in range (0, sigma_limit).
If set to 0 sigma will be computed as `sigma = 0.3*((ksize-1)*0.5 - 1) + 0.8`. Default: 0.
always_apply (bool): Whether to always apply the transform. Default: False.
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image
Image types:
uint8, float32
"""
transform = A.Compose([A.augmentations.transforms.GaussianBlur(blur_limit, sigma_limit, always_apply, p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# GlassBlur
def GlassBlur (image,sigma=0.7, max_delta=4, iterations=2, always_apply=False, mode='fast', p=1.0):
"""Apply glass noise to the input image.
Args:
sigma (float): standard deviation for Gaussian kernel.
max_delta (int): max distance between pixels which are swapped.
iterations (int): number of repeats.
Should be in range [1, inf). Default: (2).
mode (str): mode of computation: fast or exact. Default: "fast".
p (float): probability of applying the transform. Default: 1.0.
Targets:
image
Image types:
uint8, float32
Reference:
| https://arxiv.org/abs/1903.12261
| https://github.com/hendrycks/robustness/blob/master/ImageNet-C/create_c/make_imagenet_c.py
"""
transform = A.Compose([A.augmentations.transforms.GlassBlur(sigma, max_delta, iterations, always_apply, mode, p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# HistogramMatching
"""
def HistogramMatching (image,reference_images, blend_ratio=(0.5, 1.0), read_fn="", always_apply=False, p=1.0):
Apply histogram matching to an input image. This manipulates the pixels of the input image so that its
histogram matches the histogram of the reference image. If the images have multiple channels, the matching is
done independently for each channel, as long as the number of channels is equal in the input image and the
reference image.
Histogram matching can be used as a lightweight normalization for image processing, such as feature matching,
especially in circumstances where the images have been taken from different sources or in different conditions
(i.e. lighting).
See: https://scikit-image.org/docs/dev/auto_examples/color_exposure/plot_histogram_matching.html
Args:
image (numpy.ndarray): Input image.
reference_images (List[str] or List[numpy.ndarray]): List of file paths for reference images or list of
reference images.
blend_ratio (Tuple[float, float]): Tuple of min and max blend ratio. Matched image will be blended with
original with random blend factor for increased diversity of generated images.
read_fn (Callable): User-defined function to read image. Function should get image path and return numpy
array of image pixels.
always_apply (bool): If True, the transform is always applied to the image.
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image
Image types:
uint8, uint16, float32
Returns:
numpy.ndarray: Transformed image.
transform = A.Compose([A.augmentations.domain_adaptation.HistogramMatching(reference_images, blend_ratio, read_fn, always_apply, p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
"""
# HueSaturationValue
def HueSaturationValue (image,hue_shift_limit=20, sat_shift_limit=30, val_shift_limit=20, always_apply=False, p=1.0):
"""Randomly change hue, saturation and value of the input image.
Args:
image (numpy.ndarray): Input image.
hue_shift_limit (int or tuple of ints): Range for changing hue. If hue_shift_limit is a single int, the range
will be (-hue_shift_limit, hue_shift_limit). Default: 20.
sat_shift_limit (int or tuple of ints): Range for changing saturation. If sat_shift_limit is a single int,
the range will be (-sat_shift_limit, sat_shift_limit). Default: 30.
val_shift_limit (int or tuple of ints): Range for changing value. If val_shift_limit is a single int, the range
will be (-val_shift_limit, val_shift_limit). Default: 20.
always_apply (bool): If True, apply the transform to all input images. If False, apply the transform to
randomly selected images. Default: False.
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image
Image types:
uint8, float32
"""
transform = A.Compose([
A.augmentations.transforms.HueSaturationValue(hue_shift_limit=hue_shift_limit,
sat_shift_limit=sat_shift_limit,
val_shift_limit=val_shift_limit,
always_apply=always_apply,
p=p)
])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# ISONoise
def ISONoise (image,color_shift=(0.01, 0.05), intensity=(0.1, 0.5), always_apply=False, p=1.0):
"""Apply camera sensor noise to the input image.
Args:
color_shift (float, float): Variance range for color hue change.
Measured as a fraction of 360 degree Hue angle in HLS colorspace. Default: (0.01, 0.05).
intensity ((float, float): Multiplicative factor that controls the strength
of color and luminance noise. Default: (0.1, 0.5).
always_apply (bool): Whether to always apply the transform. Default: False.
p (float): Probability of applying the transform. Default: 0.5.
Targets:
image
Image types:
uint8
Returns:
numpy.ndarray: Transformed image.
"""
transform = A.Compose([A.augmentations.transforms.ISONoise(color_shift, intensity, always_apply, p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# ImageCompression
"""
def ImageCompression (image,quality_lower=99, quality_upper=100, compression_type=None, always_apply=False, p=1.0):
Decrease Jpeg, WebP compression of an image.
Args:
image (numpy.ndarray): Input image.
quality_lower (float): Lower bound on the image quality.
Should be in [0, 100] range for jpeg and [1, 100] for webp.
quality_upper (float): Upper bound on the image quality.
Should be in [0, 100] range for jpeg and [1, 100] for webp.
compression_type (ImageCompressionType): Should be ImageCompressionType.JPEG or ImageCompressionType.WEBP.
Default: ImageCompressionType.JPEG
always_apply (bool): Whether to always apply the transformation.
p (float): Probability of applying the transform. Default: 1.0.
Returns:
numpy.ndarray: Transformed image.
Targets:
image
Image types:
uint8, float32
transform = A.Compose([A.augmentations.transforms.ImageCompression(quality_lower, quality_upper, compression_type, always_apply, p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
"""
# InvertImg
def InvertImg(image,p=1.0):
"""
Invert the input image by subtracting pixel values from 255.
Args:
p (float): probability of applying the transform. Default: 1.0.
Targets:
image
Image types:
uint8
"""
transform = A.Compose([A.augmentations.transforms.InvertImg(p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# MedianBlur
def MedianBlur (image,blur_limit=7, always_apply=False, p=1.0):
"""
Apply median blur to the input image using a random aperture linear size.
Args:
image: Input image.
blur_limit (tuple[int]): Maximum aperture linear size for blurring the input image.
Must be odd and in range [3, inf). Default: (3, 7).
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image
Image types:
uint8, float32
"""
transform = A.Compose([A.augmentations.transforms.MedianBlur(blur_limit, always_apply=False, p=p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# MotionBlur
def MotionBlur(image,blur_limit=7,p=1.0):
"""Apply motion blur to the input image using a random-sized kernel.
Args:
image (numpy.ndarray): input image.
blur_limit (tuple[int]): maximum kernel size for blurring the input image. Should be in range [3, inf).
Default: (3, 7).
p (float): probability of applying the transform. Default: 1.0.
Returns:
numpy.ndarray: transformed image.
Targets:
image
Image types:
uint8, float32
"""
transform = A.Compose([A.augmentations.transforms.MotionBlur(blur_limit, p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# MultiplicativeNoise
def MultiplicativeNoise (image,multiplier=(0.9, 1.1), per_channel=False, elementwise=False, always_apply=False, p=1.0):
"""
Multiply image to random number or array of numbers.
Args:
image: Input image.
multiplier (float or tuple of floats): If a single float is provided, the image will be multiplied by this number.
If a tuple of floats is provided, the multiplier will be in the range [multiplier[0], multiplier[1]).
Default: (0.9, 1.1).
per_channel (bool): If False, the same values for all channels will be used.
If True, sample values for each channel will be used. Default: False.
elementwise (bool): If False, all pixels in an image will be multiplied with a random value sampled once.
If True, image pixels will be multiplied with values that are pixelwise randomly sampled. Default: False.
always_apply (bool): If True, apply the transform to all images. If False, apply the transform to some images.
Default: False.
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image
Image types:
Any
"""
transform = A.Compose([A.augmentations.transforms.MultiplicativeNoise(multiplier, per_channel, elementwise, always_apply, p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# Normalize
def Normalize (image,mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), max_pixel_value=255.0, always_apply=False, p=1.0):
"""
Normalize the input image by applying the formula: `img = (img - mean * max_pixel_value) / (std * max_pixel_value)`
Args:
image (numpy.ndarray): input image
mean (float or list of float): mean values
std (float or list of float): standard deviation values
max_pixel_value (float): maximum possible pixel value
always_apply (bool): whether to apply the transform always or not
p (float): probability of applying the transform
Targets:
image
Image types:
uint8, float32
Returns:
numpy.ndarray: normalized image
"""
transform = A.Compose([A.augmentations.transforms.Normalize(mean, std, max_pixel_value, always_apply, p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# PixelDistributionAdaptation
"""
def PixelDistributionAdaptation (image,reference_images, blend_ratio=(0.25, 1.0), read_fn='', transform_type='pca', always_apply=False, p=1.0):
1.0), read_fn='', transform_type='pca', always_apply=False, p=1.0):
Apply pixel-level domain adaptation by fitting a simple transform (such as PCA, StandardScaler, or MinMaxScaler)
on both the original and reference image, transforms the original image with a transform trained on this
image, and then performs an inverse transformation using a transform fitted on the reference image.
Args:
image (ndarray): input image to transform.
reference_images (List[str] or List[ndarray]): list of file paths for reference images or list of reference images.
blend_ratio (tuple): tuple of min and max blend ratio. Matched image will be blended with original with random blend
factor for increased diversity of generated images. Default: (0.25, 1.0).
read_fn (Callable): user-defined function to read image. Function should get image path and return numpy array of
image pixels. Usually it's default `read_rgb_image` when images paths are used as reference, otherwise it could
be identity function `lambda x: x` if reference images have been read in advance. Default: ''.
transform_type (str): type of transform; "pca", "standard", "minmax" are allowed. Default: 'pca'.
always_apply (bool): apply the transform always. Default: False.
p (float): probability of applying the transform. Default: 1.0.
Targets:
image
Image types:
uint8, float32
See also: https://github.com/arsenyinfo/qudida
transform = A.Compose([A.augmentations.domain_adaptation.PixelDistributionAdaptation(reference_images, blend_ratio, read_fn, transform_type, always_apply, p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
"""
# Posterize
def Posterize (image,num_bits=4, always_apply=False, p=1.0):
"""Reduce the number of bits for each color channel.
Args:
num_bits ((int, int) or int,
or list of ints [r, g, b],
or list of ints [[r1, r1], [g1, g2], [b1, b2]]): number of high bits.
If num_bits is a single value, the range will be [num_bits, num_bits].
Must be in range [0, 8]. Default: 4.
num_bits (int, tuple(int, int), list[int], list[list[int, int]]):
Number of high bits. If num_bits is a single value, the range will be [num_bits, num_bits].
Must be in range [0, 8]. Default: 4.
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image
Image types:
uint8
Returns:
The transformed image.
"""
transform = A.Compose([A.augmentations.transforms.Posterize (num_bits, always_apply, p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# RGBShift
def RGBShift (image,r_shift_limit=20, g_shift_limit=20, b_shift_limit=20, always_apply=False, p=1.0):
"""Randomly shift values for each channel of the input RGB image.
Args:
r_shift_limit (int or tuple(int, int)):
Range for changing values for the red channel. If r_shift_limit is a single
int, the range will be (-r_shift_limit, r_shift_limit). Default: (-20, 20).
g_shift_limit (int or tuple(int, int)):
Range for changing values for the green channel. If g_shift_limit is a
single int, the range will be (-g_shift_limit, g_shift_limit). Default: (-20, 20).
b_shift_limit (int or tuple(int, int)):
Range for changing values for the blue channel. If b_shift_limit is a single
int, the range will be (-b_shift_limit, b_shift_limit). Default: (-20, 20).
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image
Image types:
uint8, float32
Returns:
The transformed image.
"""
transform = A.Compose([A.augmentations.transforms.RGBShift (r_shift_limit, g_shift_limit, b_shift_limit, always_apply, p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# Sharpen
def Sharpen (image,alpha=(0.2, 0.5), lightness=(0.5, 1.0), always_apply=False, p=1.0):
"""Sharpen the input image and overlays the result with the original image.
Args:
alpha (tuple(float, float)):
Range to choose the visibility of the sharpened image. At 0, only the original image is
visible, at 1.0 only its sharpened version is visible. Default: (0.2, 0.5).
lightness (tuple(float, float)):
Range to choose the lightness of the sharpened image. Default: (0.5, 1.0).
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image
Returns:
The transformed image.
"""
transform = A.Compose([A.augmentations.transforms.Sharpen (alpha, lightness, always_apply, p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# Solarize
def Solarize (image,threshold=128, always_apply=False, p=1.0):
"""
Apply the Solarize transformation to invert all pixel values above the threshold. Invert all pixel values above a threshold.
Args:
image (numpy.ndarray):
Input image.
threshold ((int, int) or int, or (float, float) or float, optional):
Range for solarizing threshold. If threshold is a single value, the range will be [threshold, threshold].
Default is 128.
p (float, optional):
Probability of applying the transform. Default is 1.0.
Returns:
numpy.ndarray:
Transformed image.
"""
transform = A.Compose([
A.augmentations.transforms.Solarize(threshold, always_apply=True, p=p)
])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# Superpixels
def Superpixels (image, p_replace=0.1, n_segments=100, max_size=128, interpolation=1, always_apply=False, p=1.0):
"""Transform images partially/completely to their superpixel representation.
This implementation uses skimage's version of the SLIC algorithm.
Args:
image (numpy.ndarray):
Input image.
p_replace (float or tuple of float):
Defines for any segment the probability that the pixels within that segment are replaced by their
average color (otherwise, the pixels are not changed).
Examples:
- A probability of ``0.0`` would mean, that the pixels in no segment are replaced by their average color
(image is not changed at all).
- A probability of ``1.0`` would mean, that around half of all segments are replaced by their average color.
- A probability of ``1.0`` would mean, that all segments are replaced by their average color (resulting in a voronoi image).
Behaviour based on chosen data types for this parameter:
- If a ``float``, then that ``flat`` will always be used.
- If ``tuple`` ``(a, b)``, then a random probability will be sampled from the interval ``[a, b]`` per image.
n_segments (int or tuple of int):
Rough target number of how many superpixels to generate (the algorithm may deviate from this number).
Lower value will lead to coarser superpixels. Higher values are computationally more intensive and will hence lead to a slowdown.
- If a single ``int``, then that value will always be used as the number of segments.
- If a ``tuple`` ``(a, b)``, then a value from the discrete interval ``[a..b]`` will be sampled per image.
max_size (int or None):
Maximum image size at which the augmentation is performed. If the width or height of an image exceeds this
value, it will be downscaled before the augmentation so that the longest side matches `max_size`.
This is done to speed up the process. The final output image has the same size as the input image.
Note that in case `p_replace` is below ``1.0``, the down-/upscaling will affect the not-replaced pixels too.
Use ``None`` to apply no down-/upscaling.
interpolation (cv2 flag):
Flag that is used to specify the interpolation algorithm. Should be one of:
- cv2.INTER_NEAREST
- cv2.INTER_LINEAR
- cv2.INTER_CUBIC
- cv2.INTER_AREA
- cv2.INTER_LANCZOS4.
Default is cv2.INTER_LINEAR.
always_apply (bool):
Apply the transformation to all images, regardless of the probability defined by `p`.
p (float):
Probability of applying the transform. Default is 1.0.
Targets:
image
Returns:
numpy.ndarray:
Transformed image.
"""
transform = A.Compose([
A.augmentations.transforms.Superpixels(p_replace=p_replace,
n_segments=n_segments,
max_size=max_size,
interpolation=interpolation,
always_apply=always_apply,
p=p)
])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# ToFloat
def ToFloat (image,max_value=None, always_apply=False, p=1.0):
"""Divide pixel values by `max_value` to get a float32 output array where all values lie in the range [0, 1.0].
If `max_value` is None the transform will try to infer the maximum value by inspecting the data type of the input
image.
See Also:
:class:`~albumentations.augmentations.transforms.FromFloat`
Args:
max_value (float): maximum possible input value. Default: None.
p (float): probability of applying the transform. Default: 1.0.
Targets:
image
Image types:
any type
"""
transform = A.Compose([A.augmentations.transforms.ToFloat(max_value, always_apply, p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# ToGray
def ToGray(image,p=1.0):
"""Converts an RGB image to grayscale. If the mean pixel value of the grayscale image is greater than 127,
invert the resulting grayscale image.
Args:
image (numpy.ndarray): Input image.
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image
Image types:
uint8, float32
"""
transform = A.Compose([A.augmentations.transforms.ToGray(p)])
transformed = transform(image=image)
transformed_image = transformed["image"]
return transformed_image
# ToSepia
def ToSepia (image,always_apply=False, p=1.0):
"""
Applies a sepia filter to the input RGB image.
Args:
image (numpy.ndarray): Input RGB image.
always_apply (bool): Indicates if the transform should always be applied. Default: False.
p (float): Probability of applying the transform. Default: 1.0.