56 lines
1.9 KiB
Python
56 lines
1.9 KiB
Python
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
|
|
#
|
|
# 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.
|
|
|
|
#This code is based on https://github.com/zhunzhong07/Random-Erasing
|
|
|
|
import math
|
|
import random
|
|
|
|
import numpy as np
|
|
|
|
|
|
class RandomErasing(object):
|
|
def __init__(self, EPSILON=0.5, sl=0.02, sh=0.4, r1=0.3,
|
|
mean=[0., 0., 0.]):
|
|
self.EPSILON = EPSILON
|
|
self.mean = mean
|
|
self.sl = sl
|
|
self.sh = sh
|
|
self.r1 = r1
|
|
|
|
def __call__(self, img):
|
|
if random.uniform(0, 1) > self.EPSILON:
|
|
return img
|
|
|
|
for _ in range(100):
|
|
area = img.shape[0] * img.shape[1]
|
|
|
|
target_area = random.uniform(self.sl, self.sh) * area
|
|
aspect_ratio = random.uniform(self.r1, 1 / self.r1)
|
|
|
|
h = int(round(math.sqrt(target_area * aspect_ratio)))
|
|
w = int(round(math.sqrt(target_area / aspect_ratio)))
|
|
|
|
if w < img.shape[1] and h < img.shape[0]:
|
|
x1 = random.randint(0, img.shape[0] - h)
|
|
y1 = random.randint(0, img.shape[1] - w)
|
|
if img.shape[0] == 3:
|
|
img[x1:x1 + h, y1:y1 + w, 0] = self.mean[0]
|
|
img[x1:x1 + h, y1:y1 + w, 1] = self.mean[1]
|
|
img[x1:x1 + h, y1:y1 + w, 2] = self.mean[2]
|
|
else:
|
|
img[0, x1:x1 + h, y1:y1 + w] = self.mean[1]
|
|
return img
|
|
return img
|