简体   繁体   中英

Data augmentation using ImageDataGenerator

I'm trying to do a simple data augmentation on my data using ImageDataGenerator. However, my generator is giving my distorted images due to the zoom parameter. I would like the random zoom to only zoom in on my data, and when it zooms in to apply the same zoom on the width and height (to avoid distorted image outputs).

gen = ImageDataGenerator(featurewise_center=False, featurewise_std_normalization=False,
                         samplewise_center = True, samplewise_std_normalization=True,
                         rotation_range=180, width_shift_range=0, height_shift_range=0,
                         shear_range=0, zoom_range=0.4, fill_mode='reflect',
                        horizontal_flip=True, rescale=1./255) 

For now, the resulting images are below.

original image output

What you're looking for is random cropping:

def random_crop(image):
    height, width = image.shape[:2]
    random_array = numpy.random.random(size=4);
    w = int((width*0.5) * (1+random_array[0]*0.5))
    h = int((height*0.5) * (1+random_array[1]*0.5))
    x = int(random_array[2] * (width-w))
    y = int(random_array[3] * (height-h))

    image_crop = image[y:h+y, x:w+x, 0:3]
    image_crop = resize(image_crop, image.shape)
    return image_crop

# Data generator 
datagen = ImageDataGenerator(rotation_range=0.2,
                             width_shift_range=0.2,
                             height_shift_range=0.2,
                             shear_range=0.2,
                             zoom_range=0.2,
                             horizontal_flip=True,
                             fill_mode='nearest',
                             preprocessing_function=random_crop)

Source here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM