RandomErasing隨機擦除python指令碼
阿新 • • 發佈:2021-01-13
隨機擦除程式碼
import os
import io
import math
import sys
import random
import argparse
import cv2
import numpy as np
def get_files(dir, suffix):
res = []
for root, directory, files in os.walk(dir):
for filename in files:
name, suf = os.path.splitext( filename)
if suf in suffix:
#res.append(filename)
res.append(os.path.join(root, filename))
return res
class RandomErasing:
"""Random erasing the an rectangle region in Image.
Class that performs Random Erasing in Random Erasing Data Augmentation by Zhong et al.
Args:
sl: min erasing area region
sh: max erasing area region
r1: min aspect ratio range of earsing region
p: probability of performing random erasing
"""
def __init__(self, p=0.5, sl=0.02, sh=0.4, r1=0.3):
self.p = p
self.s = (sl, sh)
self.r = (r1, 1/r1)
def __call__(self, img):
"""
perform random erasing
Args:
img: opencv numpy array in form of [w, h, c] range
from [0, 255]
Returns:
erased img
"""
assert len(img.shape) == 3, 'image should be a 3 dimension numpy array'
if random.random() > self.p:
return img
else:
while True:
Se = random.uniform(*self.s) * img.shape[0] * img.shape[1]
re = random.uniform(*self.r)
He = int(round(math.sqrt(Se * re)))
We = int(round(math.sqrt(Se / re)))
xe = random.randint(0, img.shape[1])
ye = random.randint(0, img.shape[0])
if xe + We <= img.shape[1] and ye + He <= img.shape[0]:
img[ye : ye + He, xe : xe + We, :] = np.random.randint(low=0, high=255, size=(He, We, img.shape[2]))
return img
if __name__ == "__main__":
img = cv2.imread('C:\\Users\\Administrator\\Desktop\\000026.jpg')
RE = RandomErasing(p=1)
for i in range(20):
img1 = RE(img.copy())
cv2.imshow("test", img1)
cv2.waitKey(1000)