Search code examples
pythonimage-processinggoogle-colaboratory

update image in directory with images of same directory


i have a directory with the set of images of different sizes ,let me show you images and their sizes

from google.colab import drive
drive.mount('/content/drive')
from PIL import Image
import glob
import time
from pylab import *
for filename in glob.iglob('/content/drive/My Drive/Colab Notebooks/Cats/*.jpg'):
  print(filename)

results of this code is :

/content/drive/My Drive/Colab Notebooks/Cats/cat1.jpg
/content/drive/My Drive/Colab Notebooks/Cats/cat2.jpg
/content/drive/My Drive/Colab Notebooks/Cats/cat3.jpg
/content/drive/My Drive/Colab Notebooks/Cats/cat4.jpg
/content/drive/My Drive/Colab Notebooks/Cats/cat5.jpg
/content/drive/My Drive/Colab Notebooks/Cats/cat6.jpg
/content/drive/My Drive/Colab Notebooks/Cats/cat7.jpg

now let us consider their sizes

from PIL import Image
import glob
import time
from pylab import *
for filename in glob.iglob('/content/drive/My Drive/Colab Notebooks/Cats/*.jpg'):
  im=array(Image.open(filename))
  print(im.shape)

result of this code is :

(410, 618, 3)
(1200, 1800, 3)
(576, 1024, 3)
(1533, 2300, 3)
(400, 600, 3)
(264, 191, 3)
(194, 259, 3)

of course i can convert it to the grayscale using following line

im=array(Image.open(filename).convert('L'))

result :

(410, 618)
(1200, 1800)
(576, 1024)
(1533, 2300)
(400, 600)
(264, 191)
(194, 259)

as you see different images have different size, what i want is to reshape all images with the same size(resize function exist for this one i know) and i want to update(replace) old image with the same image-so i have , that all images in my directory should have same sizes, how can i do it? please help me


Solution

  • Solution was much easy, then i was thinking about it, so here is my solution

    from google.colab import drive
    drive.mount('/content/drive')
    from PIL import Image
    import glob
    import time
    from pylab import *
    #directory_name ='/content/drive/My Drive/Colab Notebooks/Cats/'
    for filename in glob.iglob('/content/drive/My Drive/Colab Notebooks/Cats/*.jpg'):
      #print(filename[-8:])
      im=(Image.open(filename).convert('L'))
      im=im.resize((100,100))
      #filename=filename[-8:]
      #complete_name =directory_name+filename
      print(complete_name)
      im.save(filename)
    

    test :

    for filename in glob.iglob('/content/drive/My Drive/Colab Notebooks/Cats/*.jpg'):
       im=array((Image.open(filename).convert('L')))
       print(im.shape)
    

    result :

    (100, 100)
    (100, 100)
    (100, 100)
    (100, 100)
    (100, 100)
    (100, 100)
    (100, 100)