python - 使用同一目录的图像更新目录中的图像
问题描述
我有一个包含不同大小图像集的目录,让我向您展示图像及其大小
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)
当您看到不同的图像具有不同的大小时,我想要的是重塑具有相同大小的所有图像(我知道这个图像存在调整大小功能)并且我想用相同的图像更新(替换)旧图像 - 所以我有,我目录中的所有图像都应该具有相同的大小,我该怎么做?请帮我
解决方案
解决方案很简单,然后我正在考虑它,所以这是我的解决方案
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)
推荐阅读
- kubernetes - 如何在负载下安全终止 Pod
- c++ - 确保传递给函数的参数是唯一的
- r - 如何在 facet_wrap 中使用 ggpubr 或 rstatix 申请循环以进行多重比较统计
- graphql - 我无法解决的 Graphql 架构设计问题
- dependency-injection - 依赖注入和数据模型
- c - 使用 C 中的函数进行输入不起作用
- javascript - 使用 react-router 验证 url
- wso2 - wso2 api manager 3.1.0 中的订阅工作流实现
- azure - azure powerhsell 集成帐户合作伙伴创建身份无效
- maven - 如何使用 mvn clean install 传递自定义输入并在 mojo 类中访问此输入?