我有大约 40 个文件夹,每个文件夹中有 50 张图像,我正在向它们添加噪音。我正在做的是每次我需要为 50 个图像添加噪声时重写路径,并写下将保存文件夹的路径。
例如:
loadimage_with_noise('C:/Users/Images/folder 1/')
这将加载文件夹 1 中的每个图像,但我有多达 40 个文件夹,所以我必须一直重写所有路径到文件夹 40th执行此操作的代码:
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 个图像的文件夹,我将在不同目录中创建包含 50 个图像的新 40 个文件夹
最佳答案
你可以使用 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)
关于python - 加载目录中的每个内部文件夹并保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63619060/