yu4u / cutout-random-erasing

Cutout / Random Erasing implementation, especially for ImageDataGenerator in Keras
MIT License
167 stars 38 forks source link

Need not use while loop. #3

Closed PistonY closed 5 years ago

PistonY commented 5 years ago

Actually you could not use while loop, you need this cause by wrong range of r. In your conditions:

s = np.random.uniform(s_l, s_h)

sqrt(H*W*s/r) <= W
and
sqrt(W*H*s*r) <= H
then get rage of r shoud be
(H*s) / W <= r <= H / (W*s)

Then you code could be

import numpy as np

def get_random_eraser(p=0.5, s_l=0.02, s_h=0.4, r_1=0.3, r_2=1/0.3, v_l=0, v_h=255, pixel_level=False):
    def eraser(input_img):
        img_h, img_w, img_c = input_img.shape
        p_1 = np.random.rand()

        if p_1 > p:
            return input_img

        s = np.random.uniform(s_l, s_h)
        r = np.random.uniform(r_1, r_2)
        r = np.clip(r, (img_h*s)/img_w, img_h / (img_w*s))
        s = s * img_h * img_w
        w = int(np.sqrt(s / r))
        h = int(np.sqrt(s * r))
        left = np.random.randint(0, img_w - w)
        top = np.random.randint(0, img_h - h)

        if pixel_level:
            c = np.random.uniform(v_l, v_h, (h, w, img_c))
        else:
            c = np.random.uniform(v_l, v_h)

        input_img[top:top + h, left:left + w, :] = c

        return input_img

    return eraser

It's should be the same thing cause even you use while you just waiting the random r in right range.

yu4u commented 5 years ago

Thank you for your comment. Clipping seems to change the distribution of r. It might be enough to derive r from right range instead.

PistonY commented 5 years ago

If W==H, just set r to 0.4~1/0.4 is ok. Or you may fix range of it.

r_1 = max(r_1, (H*s) / W)
r_2 = min(r_2, H / (W*s))
Sicily-F commented 3 years ago

hi again- any chance you could check out my question here: https://github.com/yu4u/cutout-random-erasing/issues/6 I've still not had a reply from the owner of this repo