MamaPearl commited on
Commit
c01cda9
·
verified ·
1 Parent(s): fde1a86

Create augmentations.py

Browse files
Files changed (1) hide show
  1. augmentations.py +69 -0
augmentations.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch as pt
2
+ import torch.nn.functional as F
3
+ import numbers
4
+ def resize_down_up(x, scale=0.5, mode="bilinear"):
5
+ if isinstance(scale, pt.Tensor):
6
+ scale = scale.item()
7
+ _val_invars(x, scale=scale, mode=mode, type="resize")
8
+ B, C, H, W = x.shape
9
+ h_new, w_new = max(1, int(H * scale)), max(1, int(W * scale))
10
+
11
+ kwargs = {}
12
+ if mode in {"bilinear", "bicubic"}:
13
+ kwargs["align_corners"] = False
14
+
15
+ x_down = F.interpolate(x, size=(h_new, w_new), mode=mode, **kwargs)
16
+ return F.interpolate(x_down, size=(H,W), mode=mode, **kwargs)
17
+
18
+ def _val_invars(x, **kwargs):
19
+ if x.ndim != 4:
20
+ raise ValueError(f"x needs shape (B,C,H,W), got {x.shape}")
21
+ op_type = kwargs.get("type")
22
+
23
+ if op_type == "resize":
24
+ scale = kwargs.get("scale")
25
+ if not isinstance(scale, numbers.Real):
26
+ raise ValueError(f"scale must be a real number, got {scale}")
27
+ if scale <= 0.0 or scale >= 1.0:
28
+ raise ValueError(f"scale must be in (0,1), got {scale}")
29
+ mode = kwargs.get("mode")
30
+ valid_modes = {"bilinear", "bicubic", "nearest", "area"}
31
+ if mode not in valid_modes:
32
+ raise ValueError(f"mode must be one of {valid_modes}, got {mode}")
33
+ elif op_type == "decimate":
34
+ factor = kwargs.get("factor")
35
+ if factor < 2:
36
+ raise ValueError(f"decimation factor must be >=2, got {factor}")
37
+ elif op_type == "attack":
38
+ epsilon = kwargs.get("epsilon")
39
+ if not (0.0 < epsilon < 1.0):
40
+ raise ValueError(f"epsilon must be (0,1), got {epsilon}")
41
+
42
+ def decimate(x, factor=2):
43
+ # decimation: keep every factor-th pixel, then upsample back up.
44
+ _val_invars(x, factor=factor, type="decimate")
45
+ B, C, H, W = x.shape
46
+ x_dec = x[:, :, ::factor, ::factor]
47
+ return F.interpolate(x_dec, size=(H,W), mode="nearest")
48
+
49
+ def blur_decimate(x, blur):
50
+ B, C, H, W = x.shape
51
+ x_down = blur(x)
52
+ return F.interpolate(x_down, size=(H,W), mode="bilinear", align_corners=False)
53
+
54
+ def checkerboard_alias_attack(
55
+ x: pt.Tensor,
56
+ epsilon: float=0.5,
57
+ ):
58
+ _val_invars(x, epsilon=epsilon, type="attack")
59
+ B, C, H, W = x.shape
60
+ device = x.device
61
+ dtype = x.dtype
62
+
63
+ rows = pt.arange(H, device=device).view(H,1)
64
+ cols = pt.arange(W, device=device).view(1,W)
65
+ checker = ((rows + cols) % 2).float() * 2.0 - 1.0 # values in {-1, +1}
66
+ checker = checker.view( 1, 1, H, W).expand(B, C, H, W).to(dtype)
67
+
68
+ x_adv = (x + epsilon * checker).clamp(-1.0, 1.0)
69
+ return x_adv