加载目录中的每个内部文件夹并保存



我有大约40个文件夹,每个文件夹中有50个图像,我正在为它们添加噪音。我正在做的是,每当我需要在50张图像中添加噪声时,都要重写路径,并写下保存文件夹的路径。

例如:

loadimage_with_noise('C:/Users/Images/folder 1/')

这将加载文件夹1中的每个图像,但我有最多40个文件夹,所以我必须不断重写所有路径,直到文件夹40

做这件事的代码:

def loadimage_with_noise(path):
filepath_list = listdir(path)
for filepath in filepath_list:
img = Image.open(path + filepath)
img = img.resize((81, 150))
img = np.asarray(img)
noise_image = generate_noisy_image(img, 0.10)
noise_image = Image.fromarray(noise_image)
noise_image = noise_image.convert("L")
folder_index = 'folder 2/'
noise_image.save('C:/Users/Images/Noise/'+folder_index +filepath, 'JPEG')

添加噪声的功能

def generate_noisy_image(x, variance):
noise = np.random.normal(0, variance, (150, 81))
return x + noise

我想做的是自动化这项任务,而不是将图像文件夹中每个文件夹的新路径作为参数传递,我只想简单地:对于每个文件夹,加载其中的每个图像并将其保存在一个新文件夹中(噪音已经被添加(,对于我的图像文件夹中的每个文件夹

因此,对于每40个文件夹中的50个图像,我将在不同的目录中有新的40个文件夹,其中有50个图像

您可以使用os.walk

import os
for root, dirs, files in os.walk("C:/Users/Images/"):
for name in files:
image_path = os.path.join(root, name)
process_your_image(image_path)

最新更新