Last active
May 6, 2021 20:01
-
-
Save Sarfarazsajjad/b2d71d7f6c772afed124e6d4c1767972 to your computer and use it in GitHub Desktop.
Resize images in multiple directories with Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# example folder structure | |
# images | |
# ---- Tigers | |
# -------------1_tigers.jpg | |
# -------------2_tigers.jpg | |
# -------------2_tigers.png | |
# -------------n_tigers.jpg | |
# ---- Cats | |
# -------------1_cats.jpg | |
# -------------2_tcats.jpg | |
# -------------2_cats.png | |
# -------------n_cats.jpg | |
# Run the script with this steps : | |
# 1. Open your terminal, and type | |
# 2. python resizer.py {img source folder} {the size you want the image to be} {destination folder} | |
# example : | |
# python resizer.py /home/ubuntu/images/ 128 /home/ubuntu/new_images | |
# 3. Drink your coffee and watch the terminal running the process | |
import PIL | |
from PIL import Image | |
import os | |
import sys | |
def readf(): | |
try: | |
input_dir = str(sys.argv[1].rstrip('/')) #path to img source folder | |
img_size = str(sys.argv[2]) #The image size (128, 256,etc) | |
output_dir = str(sys.argv[3].rstrip('/')) #output directory | |
print "starting...." | |
print "Colecting data from %s " % input_dir | |
tclass = [ d for d in os.listdir( input_dir ) ] | |
counter = 0 | |
strdc = '' | |
hasil = [] | |
for x in tclass: | |
list_dir = os.path.join(input_dir, x ) | |
list_tuj = os.path.join(output_dir+'/', x+'/') | |
if not os.path.exists(list_tuj): | |
os.makedirs(list_tuj) | |
if os.path.exists(list_tuj): | |
for d in os.listdir(list_dir): | |
try: | |
img = Image.open(os.path.join(input_dir+'/'+x,d)) | |
wpercent = (float(img_size)/float(img.size[0])) | |
hsize = int((float(img.size[1])*float(wpercent))) | |
img = img.resize((int(img_size),hsize), Image.ANTIALIAS) | |
fname,extension = os.path.splitext(d) | |
newfile = fname+extension | |
if extension != ".jpg" : | |
newfile = fname + ".jpg" | |
img.save(os.path.join(output_dir+'/'+x,newfile),"JPEG",quality=90) | |
print "Resizing file : %s - %s " % (x,d) | |
except Exception,e: | |
print "Error resize file : %s - %s " % (x,d) | |
sys.exit(1) | |
counter +=1 | |
except Exception,e: | |
print "Error, check Input directory etc : ", e | |
sys.exit(1) | |
readf() |
If Received This Error
ModuleNotFoundError: No module named 'PIL'
Then
pip install Pillow
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
from PIL import Image
basewidth = 300
img = Image.open('somepic.jpg')
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
img.save('sompic.jpg')