Randomly selects a rectangle region in an image and erases its pixels. 'Random Erasing Data Augmentation' by Zhong et al. See https://arxiv.org/pdf/1708.04896.pdf Args: probability: The probability that the Random Erasing operation will be performed. sl: M
| 93 | return img |
| 94 | |
| 95 | class ChannelRandomErasing(object): |
| 96 | """ Randomly selects a rectangle region in an image and erases its pixels. |
| 97 | 'Random Erasing Data Augmentation' by Zhong et al. |
| 98 | See https://arxiv.org/pdf/1708.04896.pdf |
| 99 | Args: |
| 100 | probability: The probability that the Random Erasing operation will be performed. |
| 101 | sl: Minimum proportion of erased area against input image. |
| 102 | sh: Maximum proportion of erased area against input image. |
| 103 | r1: Minimum aspect ratio of erased area. |
| 104 | mean: Erasing value. |
| 105 | """ |
| 106 | |
| 107 | def __init__(self, probability = 0.5, sl = 0.02, sh = 0.4, r1 = 0.3, mean=[0.4914, 0.4822, 0.4465]): |
| 108 | |
| 109 | self.probability = probability |
| 110 | self.mean = mean |
| 111 | self.sl = sl |
| 112 | self.sh = sh |
| 113 | self.r1 = r1 |
| 114 | |
| 115 | def __call__(self, img): |
| 116 | |
| 117 | if random.uniform(0, 1) > self.probability: |
| 118 | return img |
| 119 | |
| 120 | for attempt in range(100): |
| 121 | area = img.size()[1] * img.size()[2] |
| 122 | |
| 123 | target_area = random.uniform(self.sl, self.sh) * area |
| 124 | aspect_ratio = random.uniform(self.r1, 1/self.r1) |
| 125 | |
| 126 | h = int(round(math.sqrt(target_area * aspect_ratio))) |
| 127 | w = int(round(math.sqrt(target_area / aspect_ratio))) |
| 128 | |
| 129 | if w < img.size()[2] and h < img.size()[1]: |
| 130 | x1 = random.randint(0, img.size()[1] - h) |
| 131 | y1 = random.randint(0, img.size()[2] - w) |
| 132 | if img.size()[0] == 3: |
| 133 | img[0, x1:x1+h, y1:y1+w] = self.mean[0] |
| 134 | img[1, x1:x1+h, y1:y1+w] = self.mean[1] |
| 135 | img[2, x1:x1+h, y1:y1+w] = self.mean[2] |
| 136 | else: |
| 137 | img[0, x1:x1+h, y1:y1+w] = self.mean[0] |
| 138 | return img |
| 139 | |
| 140 | return img |