The Power of Automation Using Python – Segregating Images Based on Dimensions

5/5 - (3 votes)

Project Description

Recently, I was tasked with a manual project where my client had a directory where he had downloaded tons of wallpapers/images. Some of these were Desktop wallpapers, while the other images were mobile wallpapers. He wanted me to separate these images and store them in two separate folders and also name them in a serial order.

Well! The challenge here was – there were lots of images and separating them out by checking the dimension of each image individually and then copying them to separate folders was a tedious task. This is where I thought of automating the entire process without having to do anything manually. Not only would this save my time and energy, but it also eliminates/reduces the chances of errors while separating the images.

Thus, in this project, I will demonstrate how I segregated the images as Desktop and Mobile wallpapers and then renamed them – all using a single script!

Since the client data is confidential, I will be using my own set of images (10 images) which will be a blend of desktop and mobile wallpapers. So, this is how the directory containing the images looks –

Note that it doesn’t matter how many images you have within the folder or in which order they are placed. The script can deal with any number of images. So, without further delay, let the game begin!


Step 1: Import the Necessary Libraries and Create Two Separate Directories

Since we will be working with directories and image files, we will need the help of specific libraries that allow us to work on files and folders. Here’s the list of libraries that will aid us in doing so –

  • The Image module from the PIL Library
  • The glob module
  • The os module
  • The shutil module

You will soon find out the importance of each module used in our script. Let’s go ahead and import these modules in our script.

Code:

from PIL import Image
import glob
import os
import shutil

Now that you have all the required libraries and modules at your disposal, your first task should be to create two separate folders – One to store the Desktop wallpapers and another to store the Mobile wallpapers. This can be done using the makedirs function of the os module.

TheΒ os.makedirs()Β method constructs a directory recursively. It takes the path as an input and creates the missing intermediate directories. We can even use the os.makedirsΒ method to create a folder inside an empty folder. In this case, the path to the folder you want to create will be the only single argument toΒ os.makedirs().

Code:

if not os.path.exists('Mobile Wallpapers'):
    os.makedirs('Mobile Wallpapers')
if not os.path.exists('Desktop Wallpapers'):
    os.makedirs('Desktop Wallpapers')

Wonderful! This should create a couple of folders named – ‘Mobile Wallpapers’ and ‘Desktop Wallpapers’.

πŸ“’Related Read: How to Create a Nested Directory in Python?

Step 2: Segregating the Images

Now, in order to separate the images as mobile wallpapers and desktop wallpapers, we need to work with their dimensions.

Though the following piece of code wouldn’t be a part of our script but it can prove to be instrumental in finding the dimensions (height and width) of the images.

Approach:

  • Open all the image files present in the directory one by one. To open an image the Image.open(filename) function can be used and the image can be stored as an object.
  • Once you have the image object, you can extract the height and width of the image using the height and width properties.
    • In our case, each Desktop Wallpaper had a fixed width of 1920. This is going to be instrumental in our next steps to identify if an image is a desktop image or a mobile image. In other words, every image that has a width of 1920 will be a Desktop image and every other image will be a mobile image. This might vary in your case. Nevertheless, you will certainly find a defining width or height to distinguish between the types of images.

Code:

for filename in glob.glob(r'.\Christmas\*.jpg'):
    im = Image.open(filename)
    print(f"{im.width}x{im.height}")


Output:

1920x1224
1920x1020
1920x1280
1920x1280
3264x4928
2848x4288
4000x6000
3290x5040
3278x4912
1920x1280

There we go! It is evident that all the desktop images have a width of 1920. This was also a pre-defined condition which made things easier for me to separate out the images.

πŸ“’Recommended Read: How to Get the Size of an Image with PIL in Python

Once you know that the images with 1920 width are desktop images, you can simply use an if condition to check if the width property is equal to 1920 or not. If yes, then use the shutil.copy method to copy the file from its location into the previously created Desktop Wallpapers folder. Otherwise, copy the file to the Mobile Wallpapers folder.

Code:

for filename in glob.glob(r'.\Christmas\*.jpg'):
    im = Image.open(filename)
    img_path = os.path.abspath(filename)
    if im.width == 1920:
        shutil.copy(img_path, r'.\Desktop Wallpapers')
    else:
        shutil.copy(img_path, r'.\Mobile Wallpapers')

Step 3: Rename the Files Sequentially

All that remains to be done is to open the Desktop Wallpapers folder and Mobile Wallpapers folder and rename each image inside the respective folders sequentially.

Approach:

  • Open the images in both the folders separately using the glob module.
  • Rename the images sequentially using os.rename method.
  • To maintain a sequence while naming the images you can use a counter variable and increment it after using it to name each image.

Code:

count = 1
for my_file in glob.glob(r'.\Desktop Wallpapers\*.jpg'):
    img_name = os.path.abspath(my_file)
    os.rename(img_name, r'.\Desktop Wallpapers\Desktop-img_'+str(count)+'.jpg')
    count += 1

flag = 1
for my_file in glob.glob(r'.\Mobile Wallpapers\*.jpg'):
    img_name = os.path.abspath(my_file)
    os.rename(img_name, r'.\Mobile Wallpapers\Mobile-img_'+str(flag)+'.jpg')
    flag += 1

Putting It All Together

Finally, when you put everything together, this is how the complete script looks like –

from PIL import Image
import glob
import os
import shutil

if not os.path.exists('Mobile Wallpapers'):
    os.makedirs('Mobile Wallpapers')
if not os.path.exists('Desktop Wallpapers'):
    os.makedirs('Desktop Wallpapers')

for filename in glob.glob(r'.\Christmas\*.jpg'):
    im = Image.open(filename)
    img_path = os.path.abspath(filename)
    if im.width == 1920:
        shutil.copy(img_path, r'.\Desktop Wallpapers')
    else:
        shutil.copy(img_path, r'.\Mobile Wallpapers')

count = 1
for my_file in glob.glob(r'.\Desktop Wallpapers\*.jpg'):
    img_name = os.path.abspath(my_file)
    os.rename(img_name, r'.\Desktop Wallpapers\Desktop-img_'+str(count)+'.jpg')
    count += 1

flag = 1
for my_file in glob.glob(r'.\Mobile Wallpapers\*.jpg'):
    img_name = os.path.abspath(my_file)
    os.rename(img_name, r'.\Mobile Wallpapers\Mobile-img_'+str(flag)+'.jpg')
    flag += 1 

Note that the paths used in the above script are strictly limited to my system. In your case, please specify the path where you have stored the images.

Output:

Summary

Thus, thirty lines of code can save you several hours of tedious manual work. This is how I completed my project and submitted the entire work to my happy client in a matter of one hour (even less). Now, I can download as many wallpapers as I want for my mobile and desktop screens and separate them sequentially in different directories using the same script. Isn’t that wonderful?

πŸ“’Recommended Read: How Do I List All Files of a Directory in Python?