首页 > 解决方案 > 如何在调整图像大小并将其保存到另一个文件夹时保留图像的文件名?

问题描述

我正在上一个介绍性的神经网络课程,所以请注意我的无知。也是我的第一个 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

标签: pythonneural-networkjupyter

解决方案


重用从 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.jpegthen 之类的名称,则img_filename将具有some_image我们分割的值。并丢弃.jpeg了一部分。

注意:此选项假定 original_filename 不包含.扩展名以外的任何内容。


推荐阅读