Open In Colab

Project 2: Convert and Crop All Images in a Folder with Python PIL

In [1]:
from google.colab import drive
drive.mount('/content/drive')
Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
In [2]:
import os, sys, shutil
In [3]:
os.chdir('/content/drive/My Drive')
In [4]:
print(os.getcwd())
/content/drive/My Drive
In [5]:
shutil.unpack_archive('/content/drive/My Drive/breccia.zip', '/content/drive/My Drive', 'zip')
In [6]:
import PIL
PIL.__version__
Out[6]:
'8.1.0'
In [7]:
pip uninstall PIL
WARNING: Skipping PIL as it is not installed.
In [8]:
pip install pillow==8.1.0
Requirement already satisfied: pillow==8.1.0 in /usr/local/lib/python3.6/dist-packages (8.1.0)
In [9]:
import PIL
PIL.__version__
Out[9]:
'8.1.0'
In [10]:
from PIL import Image
In [11]:
pwd
Out[11]:
'/content/drive/My Drive'
In [12]:
import os
os.chdir('/content/drive/My Drive')
In [13]:
pwd
Out[13]:
'/content/drive/My Drive'
In [14]:
mkdir breccia_jpg
mkdir: cannot create directory ‘breccia_jpg’: File exists
In [15]:
def convert():
    path1 = '/content/drive/My Drive/breccia'
    savedpath1 = '/content/drive/My Drive/breccia_jpg'
    for item in os.listdir(path1):
        fullpath1 = os.path.join(path1, item)
        if os.path.isfile(fullpath1):
            im = Image.open(fullpath1)
            im_convert = im.convert('RGB')
            fullsavedpath1 = os.path.join(savedpath1, item)
            f, e = os.path.splitext(fullsavedpath1)
            im_convert.save(f + '.jpg', 'JPEG', quality=95)
convert()
In [16]:
pwd
Out[16]:
'/content/drive/My Drive'
In [17]:
mkdir breccia_crop
In [18]:
def crop():
    path2 = '/content/drive/My Drive/breccia'
    savedpath2 = '/content/drive/My Drive/breccia_crop'
    for item in os.listdir(path2):
        fullpath2 = os.path.join(path2,item)
        if os.path.isfile(fullpath2):
            im = Image.open(fullpath2)
            im_crop = im.crop((100,100,400,400))
            fullsavedpath2 = os.path.join(savedpath2, item)
            f, e = os.path.splitext(fullsavedpath2)
            im_crop.save(f + '_cropped.png', 'png', quality=100)
crop()