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

标签 python numpy python-imaging-library

我有大约 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/

相关文章:

python - 将图像轮廓与另一图像组合

python - 如何在 python telnetlib 中禁用 telnet echo?

Python 尝试更新 2D numpy 数组中的值,但值未更新

android - "adb screencap/sdcard/screenshot.raw"产生什么格式? (没有 "-p"标志)

python - 用numba计算内积的正确方法

python - 模拟 : assert_called_once_with a numpy array as argument

python - PIL 图像未按正确顺序渲染输入的像素值

python - 运行 python 脚本,但指向另一个 python 安装

python - 混合 Bash-Python 代码段中变量的双引号与单引号

python - 在正则表达式中捕获组的奇怪行为