/
transforms.py
3284 lines (2661 loc) · 124 KB
/
transforms.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 math
import numbers
import random
import warnings
from types import LambdaType
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union, cast
from warnings import warn
import cv2
import numpy as np
from pydantic import AfterValidator, BaseModel, Field, ValidationInfo, field_validator, model_validator
from scipy import special
from scipy.ndimage import gaussian_filter
from typing_extensions import Annotated, Literal, Self, TypedDict
from albumentations import random_utils
from albumentations.augmentations.blur.functional import blur
from albumentations.augmentations.blur.transforms import BlurInitSchema, process_blur_limit
from albumentations.augmentations.utils import (
check_range,
get_num_channels,
is_grayscale_image,
is_rgb_image,
)
from albumentations.core.pydantic import (
InterpolationType,
NonNegativeFloatRangeType,
OnePlusFloatRangeType,
OnePlusIntNonDecreasingRangeType,
OnePlusIntRangeType,
ProbabilityType,
SymmetricRangeType,
ZeroOneRangeType,
check_01_range,
check_nondecreasing_range,
)
from albumentations.core.transforms_interface import (
BaseTransformInitSchema,
DualTransform,
ImageOnlyTransform,
Interpolation,
NoOp,
)
from albumentations.core.types import (
MONO_CHANNEL_DIMENSIONS,
NUM_RGB_CHANNELS,
BoxInternalType,
ChromaticAberrationMode,
ColorType,
ImageCompressionType,
ImageMode,
KeypointInternalType,
MorphologyMode,
RainMode,
ScaleFloatType,
ScaleIntType,
ScaleType,
SpatterMode,
Targets,
)
from albumentations.core.utils import format_args, to_tuple
from . import functional as F
__all__ = [
"Normalize",
"RandomGamma",
"RandomGridShuffle",
"HueSaturationValue",
"RGBShift",
"GaussNoise",
"CLAHE",
"ChannelShuffle",
"InvertImg",
"ToGray",
"ToRGB",
"ToSepia",
"ImageCompression",
"ToFloat",
"FromFloat",
"RandomBrightnessContrast",
"RandomSnow",
"RandomGravel",
"RandomRain",
"RandomFog",
"RandomSunFlare",
"RandomShadow",
"RandomToneCurve",
"Lambda",
"ISONoise",
"Solarize",
"Equalize",
"Posterize",
"Downscale",
"MultiplicativeNoise",
"FancyPCA",
"ColorJitter",
"Sharpen",
"Emboss",
"Superpixels",
"TemplateTransform",
"RingingOvershoot",
"UnsharpMask",
"PixelDropout",
"Spatter",
"ChromaticAberration",
"Morphological",
]
NUM_BITS_ARRAY_LENGTH = 3
MAX_JPEG_QUALITY = 100
TWENTY = 20
PAIR = 2
class RandomGridShuffle(DualTransform):
"""Randomly shuffles the grid's cells on an image, mask, or keypoints,
effectively rearranging patches within the image.
This transformation divides the image into a grid and then permutes these grid cells based on a random mapping.
Args:
grid (Tuple[int, int]): Size of the grid for splitting the image into cells. Each cell is shuffled randomly.
p (float): Probability that the transform will be applied.
Targets:
image, mask, keypoints
Image types:
uint8, float32
Examples:
>>> import albumentations as A
>>> transform = A.Compose([
A.RandomGridShuffle(grid=(3, 3), always_apply=False, p=1.0)
])
>>> transformed = transform(image=my_image, mask=my_mask)
>>> image, mask = transformed['image'], transformed['mask']
# This will shuffle the 3x3 grid cells of `my_image` and `my_mask` randomly.
# Mask and image are shuffled in a consistent way
Note:
This transform could be useful when only micro features are important for the model, and memorizing
the global structure could be harmful. For example:
- Identifying the type of cell phone used to take a picture based on micro artifacts generated by
phone post-processing algorithms, rather than the semantic features of the photo.
See more at https://ieeexplore.ieee.org/abstract/document/8622031
- Identifying stress, glucose, hydration levels based on skin images.
"""
class InitSchema(BaseTransformInitSchema):
grid: OnePlusIntRangeType = (3, 3)
_targets = (Targets.IMAGE, Targets.MASK, Targets.KEYPOINTS)
def __init__(self, grid: Tuple[int, int] = (3, 3), always_apply: bool = False, p: float = 0.5):
super().__init__(always_apply=always_apply, p=p)
self.grid = grid
def apply(self, img: np.ndarray, tiles: np.ndarray, mapping: List[int], **params: Any) -> np.ndarray:
return F.swap_tiles_on_image(img, tiles, mapping)
def apply_to_mask(self, mask: np.ndarray, tiles: np.ndarray, mapping: List[int], **params: Any) -> np.ndarray:
return F.swap_tiles_on_image(mask, tiles, mapping)
def apply_to_keypoint(
self,
keypoint: KeypointInternalType,
tiles: np.ndarray,
mapping: List[int],
**params: Any,
) -> KeypointInternalType:
x, y = keypoint[:2]
# Find which original tile the keypoint belongs to
for original_index, new_index in enumerate(mapping):
start_y, start_x, end_y, end_x = tiles[original_index]
# check if the keypoint is in this tile
if start_y <= y < end_y and start_x <= x < end_x:
# Get the new tile's coordinates
new_start_y, new_start_x = tiles[new_index][:2]
# Map the keypoint to the new tile's position
new_x = (x - start_x) + new_start_x
new_y = (y - start_y) + new_start_y
return (new_x, new_y, *keypoint[2:])
# If the keypoint wasn't in any tile (shouldn't happen), log a warning for debugging purposes
warn(
"Keypoint not in any tile, returning it unchanged. This is unexpected and should be investigated.",
RuntimeWarning,
)
return keypoint
def get_params_dependent_on_targets(self, params: Dict[str, Any]) -> Dict[str, np.ndarray]:
height, width = params["image"].shape[:2]
random_state = random_utils.get_random_state()
original_tiles = F.split_uniform_grid(
(height, width),
self.grid,
random_state=random_state,
)
shape_groups = F.create_shape_groups(original_tiles)
mapping = F.shuffle_tiles_within_shape_groups(shape_groups, random_state=random_state)
return {"tiles": original_tiles, "mapping": mapping}
@property
def targets_as_params(self) -> List[str]:
return ["image"]
def get_transform_init_args_names(self) -> Tuple[str, ...]:
return ("grid",)
class Normalize(ImageOnlyTransform):
"""Applies various normalization techniques to an image. The specific normalization technique can be selected
with the `normalization` parameter.
Standard normalization is applied using the formula:
`img = (img - mean * max_pixel_value) / (std * max_pixel_value)`.
Other normalization techniques adjust the image based on global or per-channel statistics,
or scale pixel values to a specified range.
Args:
mean (Optional[ColorType]): Mean values for standard normalization.
For "standard" normalization, the default values are ImageNet mean values: (0.485, 0.456, 0.406).
For "inception" normalization, use mean values of (0.5, 0.5, 0.5).
std (Optional[ColorType]): Standard deviation values for standard normalization.
For "standard" normalization, the default values are ImageNet standard deviation :(0.229, 0.224, 0.225).
For "inception" normalization, use standard deviation values of (0.5, 0.5, 0.5).
max_pixel_value (Optional[float]): Maximum possible pixel value, used for scaling in standard normalization.
Defaults to 255.0.
normalization (Literal["standard", "image", "image_per_channel", "min_max", "min_max_per_channel", "inception"])
Specifies the normalization technique to apply. Defaults to "standard".
- "standard": Applies the formula `(img - mean * max_pixel_value) / (std * max_pixel_value)`.
The default mean and std are based on ImageNet.
- "image": Normalizes the whole image based on its global mean and standard deviation.
- "image_per_channel": Normalizes the image per channel based on each channel's mean and standard deviation.
- "min_max": Scales the image pixel values to a [0, 1] range based on the global
minimum and maximum pixel values.
- "min_max_per_channel": Scales each channel of the image pixel values to a [0, 1]
range based on the per-channel minimum and maximum pixel values.
p (float): Probability of applying the transform. Defaults to 1.0.
Targets:
image
Image types:
uint8, float32
Note:
For "standard" normalization, `mean`, `std`, and `max_pixel_value` must be provided.
For other normalization types, these parameters are ignored.
"""
class InitSchema(BaseTransformInitSchema):
mean: Optional[ColorType] = Field(
default=(0.485, 0.456, 0.406),
description="Mean values for normalization, defaulting to ImageNet mean values.",
)
std: Optional[ColorType] = Field(
default=(0.229, 0.224, 0.225),
description="Standard deviation values for normalization, defaulting to ImageNet std values.",
)
max_pixel_value: Optional[float] = Field(default=255.0, description="Maximum possible pixel value.")
normalization: Literal[
"standard",
"image",
"image_per_channel",
"min_max",
"min_max_per_channel",
] = "standard"
p: ProbabilityType = 1
@model_validator(mode="after")
def validate_normalization(self) -> Self:
if (
self.mean is None
or self.std is None
or self.max_pixel_value is None
and self.normalization == "standard"
):
raise ValueError("mean, std, and max_pixel_value must be provided for standard normalization.")
return self
def __init__(
self,
mean: Optional[ColorType] = (0.485, 0.456, 0.406),
std: Optional[ColorType] = (0.229, 0.224, 0.225),
max_pixel_value: Optional[float] = 255.0,
normalization: Literal["standard", "image", "image_per_channel", "min_max", "min_max_per_channel"] = "standard",
always_apply: bool = False,
p: float = 1.0,
):
super().__init__(always_apply=always_apply, p=p)
self.mean = mean
self.std = std
self.max_pixel_value = max_pixel_value
self.normalization = normalization
def apply(self, img: np.ndarray, **params: Any) -> np.ndarray:
if self.normalization == "standard":
return F.normalize(
img,
cast(ColorType, self.mean),
cast(ColorType, self.std),
cast(float, self.max_pixel_value),
)
if self.normalization in {"image", "image_per_channel", "min_max", "min_max_per_channel"}:
return F.normalize_per_image(img, self.normalization)
raise ValueError(f"Unknown normalization type: {self.normalization}")
def get_transform_init_args_names(self) -> Tuple[str, ...]:
return ("mean", "std", "max_pixel_value", "normalization")
class ImageCompression(ImageOnlyTransform):
"""Decreases image quality by Jpeg, WebP compression of an image.
Args:
quality_range: tuple of bounds on the image quality i.e. (quality_lower, quality_upper).
Both values should be in [1, 100] range.
compression_type (ImageCompressionType): should be ImageCompressionType.JPEG or ImageCompressionType.WEBP.
Default: ImageCompressionType.JPEG
Targets:
image
Image types:
uint8, float32
"""
class InitSchema(BaseTransformInitSchema):
quality_range: OnePlusIntNonDecreasingRangeType = Field(
default=(99, 100),
description="lower and upper bound on the image quality as tuple (lower_bound, upper_bound)",
)
quality_lower: Optional[int] = Field(
default=99,
description="Lower bound on the image quality",
ge=1,
le=100,
deprecated="`quality_lower` and `quality_upper` are deprecated. "
"Use `quality_range` as tuple (quality_lower, quality_upper) instead.",
)
quality_upper: Optional[int] = Field(
default=100,
description="Upper bound on the image quality",
ge=1,
le=100,
deprecated="`quality_lower` and `quality_upper` are deprecated. "
"Use `quality_range` as tuple (quality_lower, quality_upper) instead.",
)
compression_type: ImageCompressionType = Field(
default=ImageCompressionType.JPEG,
description="Image compression format",
)
@model_validator(mode="after")
def validate_ranges(self) -> Self:
# Update the quality_range based on the non-None values of quality_lower and quality_upper
if self.quality_lower is not None or self.quality_upper is not None:
lower = self.quality_lower if self.quality_lower is not None else self.quality_range[0]
upper = self.quality_upper if self.quality_upper is not None else self.quality_range[1]
self.quality_range = (lower, upper)
# Clear the deprecated individual quality settings
self.quality_lower = None
self.quality_upper = None
# Validate the quality_range
if not (1 <= self.quality_range[0] <= MAX_JPEG_QUALITY and 1 <= self.quality_range[1] <= MAX_JPEG_QUALITY):
raise ValueError(f"Quality range values should be within [1, {MAX_JPEG_QUALITY}] range.")
return self
def __init__(
self,
quality_lower: Optional[int] = None,
quality_upper: Optional[int] = None,
compression_type: ImageCompressionType = ImageCompressionType.JPEG,
quality_range: Tuple[int, int] = (99, 100),
always_apply: bool = False,
p: float = 0.5,
):
super().__init__(always_apply, p)
self.quality_range = quality_range
self.compression_type = compression_type
def apply(self, img: np.ndarray, quality: int, image_type: Literal[".jpg", ".webp"], **params: Any) -> np.ndarray:
if img.ndim != MONO_CHANNEL_DIMENSIONS and img.shape[-1] not in (1, 3, 4):
msg = "ImageCompression transformation expects 1, 3 or 4 channel images."
raise TypeError(msg)
return F.image_compression(img, quality, image_type)
def get_params(self) -> Dict[str, Any]:
if self.compression_type == ImageCompressionType.JPEG:
image_type = ".jpg"
elif self.compression_type == ImageCompressionType.WEBP:
image_type = ".webp"
else:
raise ValueError(f"Unknown image compression type: {self.compression_type}")
return {
"quality": random_utils.randint(self.quality_range[0], self.quality_range[1] + 1),
"image_type": image_type,
}
def get_transform_init_args(self) -> Dict[str, Any]:
return {
"quality_range": self.quality_range,
"compression_type": self.compression_type.value,
}
class RandomSnow(ImageOnlyTransform):
"""Bleach out some pixel values simulating snow.
From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
Args:
snow_point_lower: lower_bond of the amount of snow. Should be in [0, 1] range
snow_point_upper: upper_bond of the amount of snow. Should be in [0, 1] range
brightness_coeff: larger number will lead to a more snow on the image. Should be >= 0
Targets:
image
Image types:
uint8, float32
"""
class InitSchema(BaseTransformInitSchema):
snow_point_lower: float = Field(default=0.1, description="Lower bound of the amount of snow", ge=0, le=1)
snow_point_upper: float = Field(default=0.3, description="Upper bound of the amount of snow", ge=0, le=1)
brightness_coeff: float = Field(default=2.5, description="Brightness coefficient, must be >= 0", ge=0)
@model_validator(mode="after")
def validate_snow_points(self) -> Self:
if self.snow_point_lower > self.snow_point_upper:
msg = "snow_point_lower must be less than or equal to snow_point_upper."
raise ValueError(msg)
return self
def __init__(
self,
snow_point_lower: float = 0.1,
snow_point_upper: float = 0.3,
brightness_coeff: float = 2.5,
always_apply: bool = False,
p: float = 0.5,
):
super().__init__(always_apply, p)
self.snow_point_lower = snow_point_lower
self.snow_point_upper = snow_point_upper
self.brightness_coeff = brightness_coeff
def apply(self, img: np.ndarray, snow_point: float, **params: Any) -> np.ndarray:
return F.add_snow(img, snow_point, self.brightness_coeff)
def get_params(self) -> Dict[str, np.ndarray]:
return {"snow_point": random.uniform(self.snow_point_lower, self.snow_point_upper)}
def get_transform_init_args_names(self) -> Tuple[str, ...]:
return ("snow_point_lower", "snow_point_upper", "brightness_coeff")
class RandomGravel(ImageOnlyTransform):
"""Add gravels.
Args:
gravel_roi: (top-left x, top-left y,
bottom-right x, bottom right y). Should be in [0, 1] range
number_of_patches: no. of gravel patches required
Targets:
image
Image types:
uint8, float32
Reference:
https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
"""
class InitSchema(BaseTransformInitSchema):
gravel_roi: Tuple[float, float, float, float] = Field(
default=(0.1, 0.4, 0.9, 0.9),
description="Region of interest for gravel placement",
)
number_of_patches: int = Field(default=2, description="Number of gravel patches", ge=1)
@model_validator(mode="after")
def validate_gravel_roi(self) -> Self:
gravel_lower_x, gravel_lower_y, gravel_upper_x, gravel_upper_y = self.gravel_roi
if not 0 <= gravel_lower_x < gravel_upper_x <= 1 or not 0 <= gravel_lower_y < gravel_upper_y <= 1:
raise ValueError(f"Invalid gravel_roi. Got: {self.gravel_roi}.")
return self
def __init__(
self,
gravel_roi: Tuple[float, float, float, float] = (0.1, 0.4, 0.9, 0.9),
number_of_patches: int = 2,
always_apply: bool = False,
p: float = 0.5,
):
super().__init__(always_apply, p)
self.gravel_roi = gravel_roi
self.number_of_patches = number_of_patches
def generate_gravel_patch(self, rectangular_roi: Tuple[int, int, int, int]) -> np.ndarray:
x1, y1, x2, y2 = rectangular_roi
area = abs((x2 - x1) * (y2 - y1))
count = area // 10
gravels = np.empty([count, 2], dtype=np.int64)
gravels[:, 0] = random_utils.randint(x1, x2, count)
gravels[:, 1] = random_utils.randint(y1, y2, count)
return gravels
def apply(self, img: np.ndarray, gravels_infos: List[Any], **params: Any) -> np.ndarray:
if gravels_infos is None:
gravels_infos = []
return F.add_gravel(img, gravels_infos)
@property
def targets_as_params(self) -> List[str]:
return ["image"]
def get_params_dependent_on_targets(self, params: Dict[str, Any]) -> Dict[str, np.ndarray]:
img = params["image"]
height, width = img.shape[:2]
x_min, y_min, x_max, y_max = self.gravel_roi
x_min = int(x_min * width)
x_max = int(x_max * width)
y_min = int(y_min * height)
y_max = int(y_max * height)
max_height = 200
max_width = 30
rectangular_rois = np.zeros([self.number_of_patches, 4], dtype=np.int64)
xx1 = random_utils.randint(x_min + 1, x_max, self.number_of_patches) # xmax
xx2 = random_utils.randint(x_min, xx1) # xmin
yy1 = random_utils.randint(y_min + 1, y_max, self.number_of_patches) # ymax
yy2 = random_utils.randint(y_min, yy1) # ymin
rectangular_rois[:, 0] = xx2
rectangular_rois[:, 1] = yy2
rectangular_rois[:, 2] = [min(tup) for tup in zip(xx1, xx2 + max_height)]
rectangular_rois[:, 3] = [min(tup) for tup in zip(yy1, yy2 + max_width)]
minx = []
maxx = []
miny = []
maxy = []
val = []
for roi in rectangular_rois:
gravels = self.generate_gravel_patch(roi)
x = gravels[:, 0]
y = gravels[:, 1]
r = random_utils.randint(1, 4, len(gravels))
sat = random_utils.randint(0, 255, len(gravels))
miny.append(np.maximum(y - r, 0))
maxy.append(np.minimum(y + r, y))
minx.append(np.maximum(x - r, 0))
maxx.append(np.minimum(x + r, x))
val.append(sat)
return {
"gravels_infos": np.stack(
[
np.concatenate(miny),
np.concatenate(maxy),
np.concatenate(minx),
np.concatenate(maxx),
np.concatenate(val),
],
1,
),
}
def get_transform_init_args_names(self) -> Tuple[str, str]:
return "gravel_roi", "number_of_patches"
class RandomRain(ImageOnlyTransform):
"""Adds rain effects.
Args:
slant_lower: should be in range [-20, 20].
slant_upper: should be in range [-20, 20].
drop_length: should be in range [0, 100].
drop_width: should be in range [1, 5].
drop_color (list of (r, g, b)): rain lines color.
blur_value (int): rainy view are blurry
brightness_coefficient (float): rainy days are usually shady. Should be in range [0, 1].
rain_type: One of [None, "drizzle", "heavy", "torrential"]
Targets:
image
Image types:
uint8, float32
Reference:
https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
"""
class InitSchema(BaseTransformInitSchema):
slant_lower: int = Field(default=-10, description="Lower bound for rain slant angle", ge=-20, le=20)
slant_upper: int = Field(default=10, description="Upper bound for rain slant angle", ge=-20, le=20)
drop_length: int = Field(default=20, description="Length of raindrops", ge=0, le=100)
drop_width: int = Field(default=1, description="Width of raindrops", ge=1, le=5)
drop_color: Tuple[int, int, int] = Field(default=(200, 200, 200), description="Color of raindrops")
blur_value: int = Field(default=7, description="Blur value for simulating rain effect", ge=0)
brightness_coefficient: float = Field(
default=0.7,
description="Brightness coefficient for rainy effect",
ge=0,
le=1,
)
rain_type: Optional[RainMode] = Field(default=None, description="Type of rain to simulate")
@model_validator(mode="after")
def validate_slant_range_and_rain_type(self) -> Self:
if self.slant_lower >= self.slant_upper:
msg = "slant_upper must be greater than or equal to slant_lower."
raise ValueError(msg)
return self
def __init__(
self,
slant_lower: int = -10,
slant_upper: int = 10,
drop_length: int = 20,
drop_width: int = 1,
drop_color: Tuple[int, int, int] = (200, 200, 200),
blur_value: int = 7,
brightness_coefficient: float = 0.7,
rain_type: Optional[RainMode] = None,
always_apply: bool = False,
p: float = 0.5,
):
super().__init__(always_apply=always_apply, p=p)
self.slant_lower = slant_lower
self.slant_upper = slant_upper
self.drop_length = drop_length
self.drop_width = drop_width
self.drop_color = drop_color
self.blur_value = blur_value
self.brightness_coefficient = brightness_coefficient
self.rain_type = rain_type
def apply(
self,
img: np.ndarray,
slant: int,
drop_length: int,
rain_drops: List[Tuple[int, int]],
**params: Any,
) -> np.ndarray:
return F.add_rain(
img,
slant,
drop_length,
self.drop_width,
self.drop_color,
self.blur_value,
self.brightness_coefficient,
rain_drops,
)
@property
def targets_as_params(self) -> List[str]:
return ["image"]
def get_params_dependent_on_targets(self, params: Dict[str, Any]) -> Dict[str, Any]:
img = params["image"]
slant = int(random.uniform(self.slant_lower, self.slant_upper))
height, width = img.shape[:2]
area = height * width
if self.rain_type == "drizzle":
num_drops = area // 770
drop_length = 10
elif self.rain_type == "heavy":
num_drops = width * height // 600
drop_length = 30
elif self.rain_type == "torrential":
num_drops = area // 500
drop_length = 60
else:
drop_length = self.drop_length
num_drops = area // 600
rain_drops = []
for _ in range(num_drops): # If You want heavy rain, try increasing this
x = random_utils.randint(slant, width + 1) if slant < 0 else random_utils.randint(0, width - slant + 1)
y = random_utils.randint(0, height - drop_length + 1)
rain_drops.append((x, y))
return {"drop_length": drop_length, "slant": slant, "rain_drops": rain_drops}
def get_transform_init_args_names(self) -> Tuple[str, ...]:
return (
"slant_lower",
"slant_upper",
"drop_length",
"drop_width",
"drop_color",
"blur_value",
"brightness_coefficient",
"rain_type",
)
class RandomFog(ImageOnlyTransform):
"""Simulates fog for the image
Args:
fog_coef_lower: lower limit for fog intensity coefficient. Should be in [0, 1] range.
fog_coef_upper: upper limit for fog intensity coefficient. Should be in [0, 1] range.
alpha_coef: transparency of the fog circles. Should be in [0, 1] range.
Targets:
image
Image types:
uint8, float32
Reference:
https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
"""
class InitSchema(BaseTransformInitSchema):
fog_coef_lower: float = Field(default=0.3, description="Lower limit for fog intensity coefficient", ge=0, le=1)
fog_coef_upper: float = Field(default=1, description="Upper limit for fog intensity coefficient", ge=0, le=1)
alpha_coef: float = Field(default=0.08, description="Transparency of the fog circles", ge=0, le=1)
@model_validator(mode="after")
def validate_fog_coefficients(self) -> Self:
if self.fog_coef_lower > self.fog_coef_upper:
msg = "fog_coef_upper must be greater than or equal to fog_coef_lower."
raise ValueError(msg)
return self
def __init__(
self,
fog_coef_lower: float = 0.3,
fog_coef_upper: float = 1,
alpha_coef: float = 0.08,
always_apply: bool = False,
p: float = 0.5,
):
super().__init__(always_apply=always_apply, p=p)
self.fog_coef_lower = fog_coef_lower
self.fog_coef_upper = fog_coef_upper
self.alpha_coef = alpha_coef
def apply(
self,
img: np.ndarray,
fog_coef: np.ndarray,
haze_list: List[Tuple[int, int]],
**params: Any,
) -> np.ndarray:
return F.add_fog(img, fog_coef, self.alpha_coef, haze_list)
@property
def targets_as_params(self) -> List[str]:
return ["image"]
def get_params_dependent_on_targets(self, params: Dict[str, Any]) -> Dict[str, Any]:
img = params["image"]
fog_coef = random.uniform(self.fog_coef_lower, self.fog_coef_upper)
height, width = imshape = img.shape[:2]
hw = max(1, int(width // 3 * fog_coef))
haze_list = []
midx = width // 2 - 2 * hw
midy = height // 2 - hw
index = 1
while midx > -hw or midy > -hw:
for _ in range(hw // 10 * index):
x = random_utils.randint(midx, width - midx - hw + 1)
y = random_utils.randint(midy, height - midy - hw + 1)
haze_list.append((x, y))
midx -= 3 * hw * width // sum(imshape)
midy -= 3 * hw * height // sum(imshape)
index += 1
return {"haze_list": haze_list, "fog_coef": fog_coef}
def get_transform_init_args_names(self) -> Tuple[str, str, str]:
return ("fog_coef_lower", "fog_coef_upper", "alpha_coef")
class RandomSunFlare(ImageOnlyTransform):
"""Simulates Sun Flare for the image
Args:
flare_roi: region of the image where flare will appear (x_min, y_min, x_max, y_max).
All values should be in range [0, 1].
angle_lower: should be in range [0, `angle_upper`].
angle_upper: should be in range [`angle_lower`, 1].
num_flare_circles_lower: lower limit for the number of flare circles.
Should be in range [0, `num_flare_circles_upper`].
num_flare_circles_upper: upper limit for the number of flare circles.
Should be in range [`num_flare_circles_lower`, inf].
src_radius:
src_color: color of the flare
Targets:
image
Image types:
uint8, float32
Reference:
https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
"""
class InitSchema(BaseTransformInitSchema):
flare_roi: Tuple[float, float, float, float] = Field(
default=(0, 0, 1, 0.5),
description="Region of the image where flare will appear",
)
angle_lower: float = Field(default=0, description="Lower bound for the angle", ge=0, le=1)
angle_upper: float = Field(default=1, description="Upper bound for the angle", ge=0, le=1)
num_flare_circles_lower: int = Field(default=6, description="Lower limit for the number of flare circles", ge=0)
num_flare_circles_upper: int = Field(
default=10,
description="Upper limit for the number of flare circles",
gt=0,
)
src_radius: int = Field(default=400, description="Source radius for the flare")
src_color: Tuple[int, int, int] = Field(default=(255, 255, 255), description="Color of the flare")
@model_validator(mode="after")
def validate_parameters(self) -> Self:
flare_center_lower_x, flare_center_lower_y, flare_center_upper_x, flare_center_upper_y = self.flare_roi
if (
not 0 <= flare_center_lower_x < flare_center_upper_x <= 1
or not 0 <= flare_center_lower_y < flare_center_upper_y <= 1
):
raise ValueError(f"Invalid flare_roi. Got: {self.flare_roi}")
if self.angle_lower >= self.angle_upper:
raise ValueError(
f"angle_upper must be greater than angle_lower. Got: {self.angle_lower}, {self.angle_upper}",
)
if self.num_flare_circles_lower >= self.num_flare_circles_upper:
msg = "num_flare_circles_upper must be greater than num_flare_circles_lower."
raise ValueError(msg)
return self
def __init__(
self,
flare_roi: Tuple[float, float, float, float] = (0, 0, 1, 0.5),
angle_lower: float = 0,
angle_upper: float = 1,
num_flare_circles_lower: int = 6,
num_flare_circles_upper: int = 10,
src_radius: int = 400,
src_color: Tuple[int, int, int] = (255, 255, 255),
always_apply: bool = False,
p: float = 0.5,
):
super().__init__(always_apply=always_apply, p=p)
self.angle_lower = angle_lower
self.angle_upper = angle_upper
self.num_flare_circles_lower = num_flare_circles_lower
self.num_flare_circles_upper = num_flare_circles_upper
self.src_radius = src_radius
self.src_color = src_color
self.flare_roi = flare_roi
def apply(
self,
img: np.ndarray,
flare_center_x: float,
flare_center_y: float,
circles: List[Any],
**params: Any,
) -> np.ndarray:
if circles is None:
circles = []
return F.add_sun_flare(
img,
flare_center_x,
flare_center_y,
self.src_radius,
self.src_color,
circles,
)
@property
def targets_as_params(self) -> List[str]:
return ["image"]
def get_params_dependent_on_targets(self, params: Dict[str, Any]) -> Dict[str, Any]:
img = params["image"]
height, width = img.shape[:2]
angle = 2 * math.pi * random.uniform(self.angle_lower, self.angle_upper)
(flare_center_lower_x, flare_center_lower_y, flare_center_upper_x, flare_center_upper_y) = self.flare_roi
flare_center_x = random.uniform(flare_center_lower_x, flare_center_upper_x)
flare_center_y = random.uniform(flare_center_lower_y, flare_center_upper_y)
flare_center_x = int(width * flare_center_x)
flare_center_y = int(height * flare_center_y)
num_circles = random_utils.randint(self.num_flare_circles_lower, self.num_flare_circles_upper + 1)
circles = []
x = []
y = []
def line(t: float) -> Tuple[float, float]:
return (flare_center_x + t * math.cos(angle), flare_center_y + t * math.sin(angle))
for t_val in range(-flare_center_x, width - flare_center_x, 10):
rand_x, rand_y = line(t_val)
x.append(rand_x)
y.append(rand_y)
for _ in range(num_circles):
alpha = random_utils.uniform(0.05, 0.2)
r = random_utils.randint(0, len(x))
rad = random.randint(1, max(height // 100 - 2, 2))
r_color = random.randint(max(self.src_color[0] - 50, 0), self.src_color[0])
g_color = random.randint(max(self.src_color[1] - 50, 0), self.src_color[1])
b_color = random.randint(max(self.src_color[2] - 50, 0), self.src_color[2])
circles += [
(
alpha,
(int(x[r]), int(y[r])),
pow(rad, 3),
(r_color, g_color, b_color),
),
]
return {
"circles": circles,
"flare_center_x": flare_center_x,
"flare_center_y": flare_center_y,
}
def get_transform_init_args(self) -> Dict[str, Any]:
return {
"flare_roi": self.flare_roi,
"angle_lower": self.angle_lower,
"angle_upper": self.angle_upper,
"num_flare_circles_lower": self.num_flare_circles_lower,
"num_flare_circles_upper": self.num_flare_circles_upper,
"src_radius": self.src_radius,
"src_color": self.src_color,
}
class RandomShadow(ImageOnlyTransform):
"""Simulates shadows for the image
Args:
shadow_roi: region of the image where shadows
will appear. All values should be in range [0, 1].
num_shadows_limit: Lower and upper limits for the possible number of shadows.
shadow_dimension: number of edges in the shadow polygons
Targets:
image
Image types:
uint8, float32
Reference:
https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
"""