Randomly mask out one or more patches from an image. 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.
| 54 | return image, target |
| 55 | |
| 56 | class Cutout(object): |
| 57 | """Randomly mask out one or more patches from an image. |
| 58 | https://github.com/uoguelph-mlrg/Cutout/blob/master/util/cutout.py |
| 59 | Args: |
| 60 | n_holes (int): Number of patches to cut out of each image. |
| 61 | length (int): The length (in pixels) of each square patch. |
| 62 | """ |
| 63 | def __init__(self, n_holes=2, length=100): |
| 64 | self.n_holes = n_holes |
| 65 | self.length = length |
| 66 | |
| 67 | def __call__(self, img, target): |
| 68 | """ |
| 69 | Args: |
| 70 | img (Tensor): Tensor image of size (C, H, W). |
| 71 | Returns: |
| 72 | Tensor: Image with n_holes of dimension length x length cut out of it. |
| 73 | """ |
| 74 | h = img.size(1) |
| 75 | w = img.size(2) |
| 76 | mask = np.ones((h, w), np.float32) |
| 77 | |
| 78 | for n in range(self.n_holes): |
| 79 | y = np.random.randint(h) |
| 80 | x = np.random.randint(w) |
| 81 | y1 = np.clip(y - self.length // 2, 0, h) |
| 82 | y2 = np.clip(y + self.length // 2, 0, h) |
| 83 | x1 = np.clip(x - self.length // 2, 0, w) |
| 84 | x2 = np.clip(x + self.length // 2, 0, w) |
| 85 | mask[y1: y2, x1: x2] = 0. |
| 86 | |
| 87 | mask = torch.from_numpy(mask) |
| 88 | mask = mask.expand_as(img) |
| 89 | img = img * mask |
| 90 | |
| 91 | return img, target |
| 92 | |
| 93 | |
| 94 | class RandomErasing(object): |