How To Compress the Images In Python without Resize or image cropping

Question:

I have an image processing problem and 100 image dataset.
now im trying to reduce the image pixel size , that means converting the larger images to smaller image pixel size(not cropping).
Im already trying some python code , but thats cropping the image
Is there any python tool or method to reduce the image pixel size.

I have tried some methods that already available , but that’s cropping my image

Thanks in adavance

Asked By: jane doe

||

Answers:

import PIL # if I remember correctly, this is not a standard library

for i, imagePath in enumerate(imagePaths):
    try:
        img = PIL.Image.open(imagePath, mode='r')
    except ValueError, FileNotFoundError, PIL.UnidentifiedImageError:
        print(f"Could not process image n°{i}. Skipping")
        continue
    img.resize((newWidth, newHeight), PIL.Image.ANTIALIAS)
    img.save(f"new_img/resized_nb_{i}")

Should do the trick.

Now of course, if you don’t want to use PIL, and your new size is a divider of the old one (for example (100 x 200) -> (10, 20)), you can always do some horrendious inline array computation :

img : np.ndarray # we will use a numpy array here, so long as you can __getitem__ a pixel, it should work.
newImg = np.array([
     [ 
      img[ x*int(oldSizeX/newSizeX), y*int(oldSizeY/newSizeY) ]
      for x in range newSizeX
     ]
     for y in range newSizeY
    ])

where you simply go and fetch the pixels you need and put them in your new array.

Answered By: Alex SHP