根据像素值向图像添加噪声

Adding noise to image based on pixel value

我想根据百分比向灰度图像添加高斯噪声

我想将眼睛区域中任何像素强度值的 5% 作为噪声添加到整个图像,所以我想做的是 select 眼睛区域中的任何像素并给出它们简单的像素强度向整个图像添加 5% 的高斯噪声。

def generate_noisy_image(x, variance):
    noise = np.random.normal(0, variance, (1, x.shape[0]))
    return x + noise

def loadimage(path):
    filepath_list = listdir(path)
    for filepath in filepath_list:
        img = Image.open(path + filepath)
        img = img.resize((81, 150))
        img = np.asarray(img)
        generate_noisy_image(img, 0.025)
        img = Image.fromarray(img)
        img.save('C:/Users/noisy-images/'+filepath, 'JPEG')



loadimage('C:/Users/my_images/')

ValueError: operands could not be broadcast together with shapes (150,81) (1,150)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-96-1bebb687f5e7> in <module>
     11 
     12 
---> 13 loadimage('source path from images')
     14 

<ipython-input-96-1bebb687f5e7> in loadimage(path)
      5         img = img.resize((81, 150))
      6         img = np.asarray(img)
----> 7         generate_noisy_image(img, 0.025)
      8         print(generate_noisy_image.shape)
      9         img = Image.fromarray(img)

<ipython-input-95-7cc3346953f6> in generate_noisy_image(x, variance)
      1 def generate_noisy_image(x, variance):
      2     noise = np.random.normal(0, variance, (1, x.shape[0]))
----> 3     return x + noise

非常基本的示例,修改 np.array 的 dims 使其工作。

import numpy as np


def generate_noisy_image(x: np.array, variance: float) -> np.array:
    noise = np.random.normal(loc=0, scale=variance, size=x.shape)
    return x + noise


if __name__ == "__main__":
    img_2D = np.random.random(size=(81, 150))
    img_2D_fake = generate_noisy_image(x=img_2D, variance=0.05)

    var = np.var(img_2D_fake - img_2D)
    sigma_by_var = var ** 0.5

    sigma = np.std(img_2D_fake - img2D)


    print(f"variance={var}\nsigma_by_var={sigma_by_var}\nsigma={sigma}")

请记住,标准差是方差的平方根。在上面的示例中,它应该打印一个 var ~0.0025 和一个 std ~0.05。