Filtering Images based on size attributes in Python?

PythonProgrammingServer Side Programming

Python provides multiple libraries for image processing including Pillow, Python Imaging library, scikit-image or OpenCV.

We are going to use Pillow library for image processing here as it offers multiple standard procedures for image manipulation and supports the range of image file formats such as jpeg, png, gif, tiff, bmp and others.

Pillow library is built on top of Python Imaging Library(PIL) and provides more features than its parent library(PIL).

Installation

We can install pillow using pip, so just type following in the command terminal −

$ pip install pillow

Basic operation on a pillow

Let’s some basic operation on images using pillow library.

from PIL import Image
image = Image.open(r"C:\Users\rajesh\Desktop\imagefolder\beach-parga.jpg")
image.show()
# The file format of the source file.
# Output: JPEG
print(image.format)

# The pixel format used by the image. Typical values are “1”, “L”, “RGB”, or “CMYK.”
# Output: RGB
print(image.mode)

# Image size, in pixels. The size is given as a 2-tuple (width, height).
# Output: (2048, 1365)
print(image.size)


# Colour palette table, if any.
#Output: None
print(image.palette)

Output

JPEG
RGB
(2048, 1365)
None

Filter images based on size

Below program will reduce the size of all the images from a particular path(default path: current working directory). We can change the max_height, max_width or extension of the image in the below-given program:

Code

import os
from PIL import Image

max_height = 900
max_width = 900
extensions = ['JPG']

path = os.path.abspath(".")
def adjusted_size(width,height):
   if width > max_width or height>max_height:
      if width > height:
         return max_width, int (max_width * height/ width)
      else:
         return int (max_height*width/height), max_height
   else:
      return width,height

if __name__ == "__main__":
   for img in os.listdir(path):
      if os.path.isfile(os.path.join(path,img)):
         img_text, img_ext= os.path.splitext(img)
         img_ext= img_ext[1:].upper()
         if img_ext in extensions:
            print (img)
            image = Image.open(os.path.join(path,img))
            width, height= image.size
            image = image.resize(adjusted_size(width, height))
            image.save(os.path.join(path,img))

Output

another_Bike.jpg
clock.JPG
myBike.jpg
Top-bike-wallpaper.jpg

On running above script, the size of the images present in the present working directory (which is currently pyton script folder), will have a maximum size of 900(width/height).

raja
Published on 12-Mar-2019 17:11:47
Advertisements