Saad Farooq
Saad Farooq

Reputation: 99

How do I resize images in python for machine learning?

I used a dataset of images for machine learning training. Each image had a width of 64px and a height of 64px as well. Now, I want to test my machine learning model using images from google. The problem is that google images are larger than training images, and I want to resize them so that their height and width are 64px (just like the images in the training set). Is there any way to do this in python? I did find some methods, but all of them maintain aspect ratio. So, I am unable to achieve 64 by 64 size.

Upvotes: 0

Views: 9593

Answers (2)

Saad Farooq
Saad Farooq

Reputation: 99

I found the function in PIL that resizes the image and does not maintain the aspect ratio.

from PIL import Image
image = Image.open('./dataset/image.jpeg')
image= image.resize((64,64))

Upvotes: 1

Thaer A
Thaer A

Reputation: 2323

You can use python-resize-image.

Install package:

pip install python-resize-image

Example:

from PIL import Image
from resizeimage import resizeimage

#open image file
with open('image.jpg', 'r+b') as fd_img:
    # create a PIL Image from file
    img = Image.open(fd_img)
    # resize image (contain)
    img = resizeimage.resize_contain(img, [64, 64])
    # covert to RBA incase it's RGBA
    img = img.convert("RGB")
    # save image
    img.save('resized-image.jpg', img.format)

Upvotes: 0

Related Questions