Posted by: xSicKxBot - 12-20-2022, 08:36 AM - Forum: Python
- No Replies
The Power of Automation Using Python – Segregating Images Based on Dimensions
Rate this post
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’.
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}")
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.
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?
This game is free to keep if claimed by December 20, 2022 5:00 PM or in a day
- Click on the GET Button - Verify that the price is zero - Click on the Place Order Button - Thats it, the game will be added to you Epic Games Account
We are welcoming everyone to join our discord[discord.gg]. We are more active there on finding giveaways, small or large, and there are daily raffles you can participate.
Become the King and wrestle over control of Europe in this fresh take on medieval real-time grand strategy.
Knights of Honor II: Sovereign includes all the depth players desire while being the gate-way game to the grand strategy genre, presenting the world as a living, breathing miniature, alive and ripe for the taking. Choose your royal court carefully and determine the destiny of your people, be it riches, conquest, intrigue, trade, or defeat! Raise armies to defend your lands or take war to the enemy - even jump into battle directly in action-packed RTS combat.
The path is open: become the true Sovereign of your people.
JDK 15.0.1, 11.0.9, 8u271, and 7u281 Have Been Released!
The Java SE 15.0.1, 11.0.9, 8u271, and 7u281 update releases are now available. You can download the latest JDK releases from the Java SE Downloads page. OpenJDK 15.0.1 is available on http://jdk.java.net/15/. New Features, Changes, and Notable Bug Fixes For information about the new features, chang...
Posted by: xSicKxBot - 12-19-2022, 10:32 AM - Forum: Python
- No Replies
This is How I Played a Sinus Tone in My Jupyter Notebook (Python)
5/5 – (1 vote)
What/Why? I want to write a simple Python script that warns me if crypto price data (e.g., BTC) crosses a certain threshold. This can be useful for trading or some other apps, so I thought it would be fun to do it.
The tutorial in front of you simply documents my learnings on creating a sinus tone in my Jupyter Notebook—so it may benefit you as well.
If you want the whole tutorial on my mini project, you can check it out here on the Finxter blog:
Challenge: Write Python code in a Jupyter Notebook that creates a sinus tone when executed.
Solution
The easy way to solve this challenge is the following.
This code creates a sine wave with a frequency of 500 Hz and plays it in the IPython environment. The wave is created using the NumPy library by specifying the frequency and the length of the wave (15000*2). The rate of the wave is set to 10000 Hz and autoplay is set to True so that the wave will start playing immediately.
import numpy as np
from IPython.display import Audio # Create the tone as a NumPy Sinus Wave
wave = np.sin(2*np.pi*500*np.arange(15000*2)/15000) # Play the Sinus Wave (tone)
Audio(wave, rate=10000, autoplay=True)
This generates the following beep sound in your Jupyter Notebook:
What happens if you change the rate argument of the Audio() function call to be 20000 instead of 10000?
# Play the Sinus Wave (tone)
Audio(wave, rate=20000, autoplay=True)
The beep sound tone gets higher:
You can play around with the Jupyter notebook here:
But what if you don’t have a Jupyter notebook but a normal Python script (Win/Linux/macOS)?
In that case, you cannot use the IPython library. Instead, follow the steps outlined in the following tutorial on the Finxter blog—you still can play beep sounds!
This game is free to keep if claimed by December 19, 2022 5:00 PM or in a day
- Click on the GET Button - Verify that the price is zero - Click on the Place Order Button - Thats it, the game will be added to you Epic Games Account
We are welcoming everyone to join our discord[discord.gg]. We are more active there on finding giveaways, small or large, and there are daily raffles you can participate.
Posted by: xSicKxBot - 12-19-2022, 10:30 AM - Forum: Lounge
- No Replies
Fortnite And My Hero Academia: How To Get Deku's Smash Mythic Weapon
My Hero Academia has arrived in Fortnite, and over the next two weeks, it's going to have a huge impact on how you play. That's because this collab isn't just about item shop cosmetics--though it certainly does have those. But on top of that, the island is now home to a new MHA-themed Mythic weapon: Deku's Smash.
Remember how the Kamehameha was basically a giant laser that would melt anything that you pointed it at--provided you could survive the lengthy charge-up time? The Deku's Smash is a pretty similar concept, with the main difference being that it's more like you're throwing a very large bomb.
The deepest, most intricate simulation of a world that's ever been created. The legendary Dwarf Fortress is now on Steam. Build a fortress and try to help your dwarves survive against a deeply generated world.
JDK 15 is live! Download it from the Java SE Downloads page. See the JDK 15 Release Notes for detailed information about this release. The following are some of the important additions and updates in Java SE 15 and JDK 15: Text Blocks, first previewed in Java SE 13, is a permanent feature in this re...