簡體   English   中英

如何在調整圖像大小並將其保存到另一個文件夾時保留圖像的文件名?

[英]How do I keep the file name of an image when resizing it and saving it to another folder?

我在介紹神經網絡 class 所以請注意我的無知。 也是我的第一個 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

另一種選擇,我們可以使用 python str的內置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之類的名稱,那么img_filename將具有我們分割的值some_image 並丟棄了.jpeg的一部分。

注意:此選項假定 original_filename 不包含任何. 除了擴展名。

我假設圖像名稱在 path1 上。 如果是這樣,您可以通過以下方式從那里獲取圖像名稱:

x=path1.rsplit('/',1)[1]

我們在最后一個斜杠上拆分 path1 並通過索引獲取圖像名稱字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM