Randomly mask out one or more patches from an image. @author: uoguelph-mlrg (https://github.com/uoguelph-mlrg/Cutout/blob/master/util/cutout.py) Args: n_holes (int): Number of patches to cut out of each image. length (int): The length (in pixels) of each square patch.
| 9 | |
| 10 | |
| 11 | class Cutout(object): |
| 12 | """Randomly mask out one or more patches from an image. |
| 13 | @author: uoguelph-mlrg |
| 14 | (https://github.com/uoguelph-mlrg/Cutout/blob/master/util/cutout.py) |
| 15 | Args: |
| 16 | n_holes (int): Number of patches to cut out of each image. |
| 17 | length (int): The length (in pixels) of each square patch. |
| 18 | """ |
| 19 | |
| 20 | def __init__(self, n_holes, length): |
| 21 | if n_holes < 0 or length < 0: |
| 22 | raise ValueError("Must set n_holes or length args for cutout") |
| 23 | self.n_holes = n_holes |
| 24 | self.length = length |
| 25 | |
| 26 | def __call__(self, img): |
| 27 | """ |
| 28 | Args: |
| 29 | img (Tensor): Tensor image of size (C, H, W). |
| 30 | Returns: |
| 31 | Tensor: Image with n_holes of dimension length x length cut out of |
| 32 | it. |
| 33 | """ |
| 34 | h = img.size(1) |
| 35 | w = img.size(2) |
| 36 | |
| 37 | mask = np.ones((h, w), np.float32) |
| 38 | |
| 39 | for n in range(self.n_holes): |
| 40 | y = np.random.randint(h) |
| 41 | x = np.random.randint(w) |
| 42 | |
| 43 | y1 = np.clip(y - self.length // 2, 0, h) |
| 44 | y2 = np.clip(y + self.length // 2, 0, h) |
| 45 | x1 = np.clip(x - self.length // 2, 0, w) |
| 46 | x2 = np.clip(x + self.length // 2, 0, w) |
| 47 | |
| 48 | mask[y1: y2, x1: x2] = 0. |
| 49 | |
| 50 | mask = torch.from_numpy(mask) |
| 51 | mask = mask.expand_as(img) |
| 52 | img = img * mask |
| 53 | |
| 54 | return img |
| 55 | |
| 56 | |
| 57 | def get_data( |