random_erasing.py 4.0 KB
Newer Older
F
Felix 已提交
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
F
Felix 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

G
gaotingquan 已提交
15 16
# This code is adapted from https://github.com/zhunzhong07/Random-Erasing, and refer to Timm(https://github.com/rwightman/pytorch-image-models).
# reference: https://arxiv.org/abs/1708.04896
G
gaotingquan 已提交
17 18

from functools import partial
F
Felix 已提交
19 20 21 22 23 24 25

import math
import random

import numpy as np


G
gaotingquan 已提交
26 27 28
class Pixels(object):
    def __init__(self, mode="const", mean=[0., 0., 0.]):
        self._mode = mode
H
HydrogenSulfate 已提交
29
        self._mean = np.array(mean)
G
gaotingquan 已提交
30

H
HydrogenSulfate 已提交
31
    def __call__(self, h=224, w=224, c=3, channel_first=False):
G
gaotingquan 已提交
32
        if self._mode == "rand":
H
HydrogenSulfate 已提交
33 34 35
            return np.random.normal(size=(
                1, 1, 3)) if not channel_first else np.random.normal(size=(
                    3, 1, 1))
G
gaotingquan 已提交
36
        elif self._mode == "pixel":
H
HydrogenSulfate 已提交
37 38 39
            return np.random.normal(size=(
                h, w, c)) if not channel_first else np.random.normal(size=(
                    c, h, w))
G
gaotingquan 已提交
40
        elif self._mode == "const":
H
HydrogenSulfate 已提交
41 42 43
            return np.reshape(self._mean, (
                1, 1, c)) if not channel_first else np.reshape(self._mean,
                                                               (c, 1, 1))
G
gaotingquan 已提交
44 45 46 47 48 49
        else:
            raise Exception(
                "Invalid mode in RandomErasing, only support \"const\", \"rand\", \"pixel\""
            )


F
Felix 已提交
50
class RandomErasing(object):
G
gaotingquan 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
    """RandomErasing.
    """

    def __init__(self,
                 EPSILON=0.5,
                 sl=0.02,
                 sh=0.4,
                 r1=0.3,
                 mean=[0., 0., 0.],
                 attempt=100,
                 use_log_aspect=False,
                 mode='const'):
        self.EPSILON = eval(EPSILON) if isinstance(EPSILON, str) else EPSILON
        self.sl = eval(sl) if isinstance(sl, str) else sl
        self.sh = eval(sh) if isinstance(sh, str) else sh
        r1 = eval(r1) if isinstance(r1, str) else r1
        self.r1 = (math.log(r1), math.log(1 / r1)) if use_log_aspect else (
            r1, 1 / r1)
        self.use_log_aspect = use_log_aspect
        self.attempt = attempt
        self.get_pixels = Pixels(mode, mean)
F
Felix 已提交
72 73

    def __call__(self, img):
G
gaotingquan 已提交
74
        if random.random() > self.EPSILON:
F
Felix 已提交
75 76
            return img

G
gaotingquan 已提交
77
        for _ in range(self.attempt):
H
HydrogenSulfate 已提交
78 79 80 81 82 83 84
            if isinstance(img, np.ndarray):
                img_h, img_w, img_c = img.shape
                channel_first = False
            else:
                img_c, img_h, img_w = img.shape
                channel_first = True
            area = img_h * img_w
F
Felix 已提交
85 86

            target_area = random.uniform(self.sl, self.sh) * area
G
gaotingquan 已提交
87 88 89
            aspect_ratio = random.uniform(*self.r1)
            if self.use_log_aspect:
                aspect_ratio = math.exp(aspect_ratio)
F
Felix 已提交
90 91 92 93

            h = int(round(math.sqrt(target_area * aspect_ratio)))
            w = int(round(math.sqrt(target_area / aspect_ratio)))

H
HydrogenSulfate 已提交
94 95 96 97 98 99 100 101 102
            if w < img_w and h < img_h:
                pixels = self.get_pixels(h, w, img_c, channel_first)
                x1 = random.randint(0, img_h - h)
                y1 = random.randint(0, img_w - w)
                if img_c == 3:
                    if channel_first:
                        img[:, x1:x1 + h, y1:y1 + w] = pixels
                    else:
                        img[x1:x1 + h, y1:y1 + w, :] = pixels
F
Felix 已提交
103
                else:
H
HydrogenSulfate 已提交
104 105 106 107
                    if channel_first:
                        img[0, x1:x1 + h, y1:y1 + w] = pixels[0]
                    else:
                        img[x1:x1 + h, y1:y1 + w, 0] = pixels[:, :, 0]
F
Felix 已提交
108 109
                return img
        return img