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 This variant of RandomErasing is intended to be applied to either a batch or single image tensor after it
| 32 | |
| 33 | |
| 34 | class RandomErasing: |
| 35 | """Randomly selects a rectangle region in an image and erases its pixels. |
| 36 | 'Random Erasing Data Augmentation' by Zhong et al. |
| 37 | See https://arxiv.org/pdf/1708.04896.pdf |
| 38 | This variant of RandomErasing is intended to be applied to either a batch |
| 39 | or single image tensor after it has been normalized by dataset mean and std. |
| 40 | Args: |
| 41 | probability: Probability that the Random Erasing operation will be performed. |
| 42 | min_area: Minimum percentage of erased area wrt input image area. |
| 43 | max_area: Maximum percentage of erased area wrt input image area. |
| 44 | min_aspect: Minimum aspect ratio of erased area. |
| 45 | mode: pixel color mode, one of 'const', 'rand', or 'pixel' |
| 46 | 'const' - erase block is constant color of 0 for all channels |
| 47 | 'rand' - erase block is same per-channel random (normal) color |
| 48 | 'pixel' - erase block is per-pixel random (normal) color |
| 49 | max_count: maximum number of erasing blocks per image, area per box is scaled by count. |
| 50 | per-image count is randomly chosen between 1 and this value. |
| 51 | """ |
| 52 | |
| 53 | def __init__( |
| 54 | self, |
| 55 | probability=0.5, |
| 56 | min_area=0.02, |
| 57 | max_area=1 / 3, |
| 58 | min_aspect=0.3, |
| 59 | max_aspect=None, |
| 60 | mode="const", |
| 61 | min_count=1, |
| 62 | max_count=None, |
| 63 | num_splits=0, |
| 64 | device="cuda", |
| 65 | cube=True, |
| 66 | ): |
| 67 | self.probability = probability |
| 68 | self.min_area = min_area |
| 69 | self.max_area = max_area |
| 70 | max_aspect = max_aspect or 1 / min_aspect |
| 71 | self.log_aspect_ratio = (math.log(min_aspect), math.log(max_aspect)) |
| 72 | self.min_count = min_count |
| 73 | self.max_count = max_count or min_count |
| 74 | self.num_splits = num_splits |
| 75 | mode = mode.lower() |
| 76 | self.rand_color = False |
| 77 | self.per_pixel = False |
| 78 | self.cube = cube |
| 79 | if mode == "rand": |
| 80 | self.rand_color = True # per block random normal |
| 81 | elif mode == "pixel": |
| 82 | self.per_pixel = True # per pixel random normal |
| 83 | else: |
| 84 | assert not mode or mode == "const" |
| 85 | self.device = device |
| 86 | |
| 87 | def _erase(self, img, chan, img_h, img_w, dtype): |
| 88 | if random.random() > self.probability: |
| 89 | return |
| 90 | area = img_h * img_w |
| 91 | count = ( |
no outgoing calls
no test coverage detected