Custom cropping function in ImageDatagenerator

79 views Asked by At

I need to Crop a square shape around a Centre point (x,y) and I try to create my custom function below.

from PIL import Image

def Crop_Image(image):
    cropsize = 224
    croplength = cropsize/2
    x = Xcentre
    y = Ycentre
    image_crop = image.crop((x-croplength, y-croplength, x+croplength, y+croplength))
    return image_crop

Then passing Crop_Image function in to the Imagedatagenerator.

datagen = ImageDataGenerator(rescale=1./255,
                             validation_split=0.2,
                             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=Crop_Image)

but in the training process, I have got some error.

AttributeError: 'numpy.ndarray' object has no attribute 'crop'

How can I solve this error?

1

There are 1 answers

9
Tino D On

At the end of the day, image is just another array, why don't you crop it like this:

image_crop = image[int(y - croplength):int(y + croplength), int(x - croplength):int(x + croplength)]

I added int in case croplength was not a full number. This is because the indexing of an array should optimally be with full integers

V2.0: with pillow function

from PIL import Image
image = Image.open("...")
def Crop_Image(image):
    cropsize = 224
    croplength = int(cropsize/2)
    x = 500
    y = 500
    image_crop = image.crop((x-croplength, y-croplength, x+croplength, y+croplength))
    return image_crop

croppedImage = Crop_Image(image)

plt.imshow(croppedImage)

This is working perfectly for me