首页 > 解决方案 > 使用同一目录的图像更新目录中的图像

问题描述

我有一个包含不同大小图像集的目录,让我向您展示图像及其大小

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)

这段代码的结果是:

/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

现在让我们考虑它们的尺寸

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)

此代码的结果是:

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

当然,我可以使用以下行将其转换为灰度

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

结果 :

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

当您看到不同的图像具有不同的大小时,我想要的是重塑具有相同大小的所有图像(我知道这个图像存在调整大小功能)并且我想用相同的图像更新(替换)旧图像 - 所以我有,我目录中的所有图像都应该具有相同的大小,我该怎么做?请帮我

标签: pythonimage-processinggoogle-colaboratory

解决方案


解决方案很简单,然后我正在考虑它,所以这是我的解决方案

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)

测试 :

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

结果 :

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

推荐阅读