如何使用 PIL .save 将不同名称的图像保存在不同的目录中?

How can I save images with different name on different directory using PIL .save?

我正在尝试从目录“./train_dataset/train_img_cropped”和“./train_dataset/train_gt_cropped”中获取 train_img 和真实图像。接下来,我想将原始图像和翻转后的图像保存在目录“./train_dataset/train_img_preprocessed”和“./train_dataset/train_gt_preprocessed”中,其名称带有“_0”、“_1”尾巴。但是将名称(文件+“_0”或“_1”)更改为未知文件扩展名时会出错。看起来 PIL 以某种方式将 _0、_1 识别为扩展名。有谁可以帮我改个名字省钱吗?

import os
import os.path
import glob

from PIL import Image

def preprocess(img_path, save_path):
targetdir = img_path
files = os.listdir(targetdir)

format = [".png"]
for (path, dirs, files) in os.walk(targetdir):

    for file, i in files:
        if file.endswith(tuple(format)):
            image = Image.open(path + "/" + file)
            image.save(save_path + "/" + file)

            flippedImage = image.transpose(Image.FLIP_LEFT_RIGHT)
            flippedImage.save(save_path + "/" + file)

            print(file + " successfully flipped!")
        
        else:
            print(path)
            print("InValid", file)

if __name__ == "__main__":
train_img_cropped_path = './train_dataset/train_img_cropped'
train_img_preprocessed_path = './train_dataset/train_img_preprocessed'

train_gt_cropped_path = './train_dataset/train_gt_cropped'
train_gt_preprocessed_path = './train_dataset/train_gt_preprocessed'



preprocess(train_img_cropped_path, train_img_preprocessed_path)
preprocess(train_gt_cropped_path, train_gt_preprocessed_path)

不确定这是否回答了您的问题,但为什么不用临时名称(例如随机字母数字字符串或 uuid)保存图像,然后使用 os.rename 更改临时文件的名称你想要的名字以 _0_1.

结尾