pythonimageimage-processingimage-resizingrescale

How can I resize and reshape images with python?


I want to work with a bunch of images (100+) and I need to keep their aspect ratios (which varies between each other), but resize them to be a maximum of 1000x1000 and have a maximum file size of 100kb.

I have tried the "optimize-images" package but I couldn't get the results I wanted because I couldn't be specific enough. I also tried resizing with imageio, but the size issue remains. I have read different sources and replies to similar issues, but have found no way of doing this.

import imageio
import os

os.chdir("C:\\Users\\abc123\\Pictures\\Resize")

im = imageio.imread("a.jpg")

small = transform.resize(im, (1000,1000), mode="symmetric", preserve_range=True)

Ideally, I will use the walk() method to find all the images in the folder, resize them to 1000x1000, maintain the aspect ratio by filling with blank the differential between the final size and the resized image, and finally apply a 0.8 or 0.75 quality reduction until the file size is =< 100 kb. I realize my code is very basic, but I'm mostly looking for directions/inspiration for how I could tackle this problem. Thanks in advance!


Solution

  • You could use skimage library.

    import numpy as np
    from skimage import data, color
    from skimage.transform import rescale, resize
    
    grayimage = color.rgb2gray(data.astronaut())
    image_rescaled = rescale(grayimage, 1.0 / 4.0, anti_aliasing=False, multichannel = False)
    image_resized = resize(grayimage, (grayimage.shape[0] / 4, grayimage.shape[1] / 4),
                           anti_aliasing=True)
    plt.imshow(np.hstack([image_rescaled, image_resized]))
    plt.title('Rescaled'+ ''.join([" "]*30) +'Resized')
    plt.show()
    

    Output:
    enter image description here

    Saving Image with Reduced File Size

    For controlling the file size while saving the image to your file system, you could use PIL library with optimize=True and quality=some_number. See this thread: How to reduce the image file size using PIL.

    References

    HowTo: Rescale and Resize using skimage Library