pytorch-image-models
117 строк · 4.8 Кб
1""" Random Erasing (Cutout)
2
3Originally inspired by impl at https://github.com/zhunzhong07/Random-Erasing, Apache 2.0
4Copyright Zhun Zhong & Liang Zheng
5
6Hacked together by / Copyright 2019, Ross Wightman
7"""
8import random9import math10
11import torch12
13
14def _get_pixels(per_pixel, rand_color, patch_size, dtype=torch.float32, device='cuda'):15# NOTE I've seen CUDA illegal memory access errors being caused by the normal_()16# paths, flip the order so normal is run on CPU if this becomes a problem17# Issue has been fixed in master https://github.com/pytorch/pytorch/issues/1950818if per_pixel:19return torch.empty(patch_size, dtype=dtype, device=device).normal_()20elif rand_color:21return torch.empty((patch_size[0], 1, 1), dtype=dtype, device=device).normal_()22else:23return torch.zeros((patch_size[0], 1, 1), dtype=dtype, device=device)24
25
26class RandomErasing:27""" Randomly selects a rectangle region in an image and erases its pixels.28'Random Erasing Data Augmentation' by Zhong et al.
29See https://arxiv.org/pdf/1708.04896.pdf
30
31This variant of RandomErasing is intended to be applied to either a batch
32or single image tensor after it has been normalized by dataset mean and std.
33Args:
34probability: Probability that the Random Erasing operation will be performed.
35min_area: Minimum percentage of erased area wrt input image area.
36max_area: Maximum percentage of erased area wrt input image area.
37min_aspect: Minimum aspect ratio of erased area.
38mode: pixel color mode, one of 'const', 'rand', or 'pixel'
39'const' - erase block is constant color of 0 for all channels
40'rand' - erase block is same per-channel random (normal) color
41'pixel' - erase block is per-pixel random (normal) color
42max_count: maximum number of erasing blocks per image, area per box is scaled by count.
43per-image count is randomly chosen between 1 and this value.
44"""
45
46def __init__(47self,48probability=0.5,49min_area=0.02,50max_area=1/3,51min_aspect=0.3,52max_aspect=None,53mode='const',54min_count=1,55max_count=None,56num_splits=0,57device='cuda',58):59self.probability = probability60self.min_area = min_area61self.max_area = max_area62max_aspect = max_aspect or 1 / min_aspect63self.log_aspect_ratio = (math.log(min_aspect), math.log(max_aspect))64self.min_count = min_count65self.max_count = max_count or min_count66self.num_splits = num_splits67self.mode = mode.lower()68self.rand_color = False69self.per_pixel = False70if self.mode == 'rand':71self.rand_color = True # per block random normal72elif self.mode == 'pixel':73self.per_pixel = True # per pixel random normal74else:75assert not self.mode or self.mode == 'const'76self.device = device77
78def _erase(self, img, chan, img_h, img_w, dtype):79if random.random() > self.probability:80return81area = img_h * img_w82count = self.min_count if self.min_count == self.max_count else \83random.randint(self.min_count, self.max_count)84for _ in range(count):85for attempt in range(10):86target_area = random.uniform(self.min_area, self.max_area) * area / count87aspect_ratio = math.exp(random.uniform(*self.log_aspect_ratio))88h = int(round(math.sqrt(target_area * aspect_ratio)))89w = int(round(math.sqrt(target_area / aspect_ratio)))90if w < img_w and h < img_h:91top = random.randint(0, img_h - h)92left = random.randint(0, img_w - w)93img[:, top:top + h, left:left + w] = _get_pixels(94self.per_pixel,95self.rand_color,96(chan, h, w),97dtype=dtype,98device=self.device,99)100break101
102def __call__(self, input):103if len(input.size()) == 3:104self._erase(input, *input.size(), input.dtype)105else:106batch_size, chan, img_h, img_w = input.size()107# skip first slice of batch if num_splits is set (for clean portion of samples)108batch_start = batch_size // self.num_splits if self.num_splits > 1 else 0109for i in range(batch_start, batch_size):110self._erase(input[i], chan, img_h, img_w, input.dtype)111return input112
113def __repr__(self):114# NOTE simplified state for repr115fs = self.__class__.__name__ + f'(p={self.probability}, mode={self.mode}'116fs += f', count=({self.min_count}, {self.max_count}))'117return fs118