python - 如何在调整图像大小并将其保存到另一个文件夹时保留图像的文件名?
问题描述
我正在上一个介绍性的神经网络课程,所以请注意我的无知。也是我的第一个 SO 帖子。
我正在尝试将数据集中一些非常高分辨率的图像调整为新数据集中的 80x80p 灰度图像。但是,当我这样做时,我想保持每个新图像的文件名与原始图像相同。我知道如何将图像重新保存到新文件中的唯一方法是通过 str(count) ,这不是我想要的。文件名对于稍后为我的数据集创建 .csv 文件很重要。
我能找到的唯一相关的SO帖子是:
但是建议的代码不起作用-不确定我是否以错误的方式进行操作。
import os
from PIL import Image
import imghdr
count=0
path1 = "/Users/..."
path2 = "/Users/..."
listing = os.listdir(path1)
for file in listing:
type = imghdr.what((path1 + file))
if type == "jpeg":
img = Image.open("/Users/..." +file).convert('LA')
img_resized = img.resize((80,80))
img_resized.save(path2 + str(count) + '.png')
count +=1
pass
pass
解决方案
重用从 for 循环中获得的原始文件名,即file
,将其拆分为文件名和扩展名,os.path.splitext()
如下所示:
import os
from PIL import Image
import imghdr
count=0
path1 = "/Users/..."
path2 = "/Users/..."
listing = os.listdir(path1)
for file in listing:
type = imghdr.what((path1 + file))
if type == "jpeg":
img = Image.open("/Users/..." +file).convert('LA')
img_resized = img.resize((80,80))
# splitting the original filename to remove extension
img_filename = os.path.splitext(file)[0]
img_resized.save(path2 + img_filename + '.png')
count +=1
pass
另一种选择,我们可以使用 pythonstr
的内置split
方法来拆分原始文件名.
并丢弃扩展名。
import os
from PIL import Image
import imghdr
count=0
path1 = "/Users/..."
path2 = "/Users/..."
listing = os.listdir(path1)
for file in listing:
type = imghdr.what((path1 + file))
if type == "jpeg":
img = Image.open("/Users/..." +file).convert('LA')
img_resized = img.resize((80,80))
# splitting the original filename to remove extension
img_filename = file.split(".")[0]
img_resized.save(path2 + img_filename + '.png')
count +=1
pass
因此,如果图像具有some_image.jpeg
then 之类的名称,则img_filename
将具有some_image
我们分割的值。并丢弃.jpeg
了一部分。
注意:此选项假定 original_filename 不包含.
扩展名以外的任何内容。
推荐阅读
- php - 将多个 DIV 链接到 Wordpress 中的多个类别
- html - svg 旋转动画(变换原点)
- reactjs - 如何使用 React Native 集成 Google 和 Facebook 登录
- python - 使用 openpyxl 在 excelsheet 中创建内部链接
- c++ - 按属性初始化 typedef struct 问题
- node.js - 在 Docker 容器中运行 Sails.js 应用程序时出现“加载 gRPC 二进制模块失败”错误
- django - Django + webpack + reactjs:如何通过单独的reactjs代码为每个url生成多个页面
- php - Laravel web.php 没有正确重定向。
- c# - 循环动态 JSON 以获取所有节点 C#
- java - SPOJ 下一个回文(Java)