I would like to add gaussian noise to images in greyscale based on percentages
I'd like to add 5% of any pixel intensity value in the eye area as noise to the whole image, so what i want to do is select any pixel inside the eye region and given their simple pixel intensity add 5% of guassian noise to the entire image.
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
Very basic example, hack around np.array
's dims to make it work.
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}")
Keep in mind the standard derivation is the root square of the variance. It should print a var ~0.0025 and a std ~0.05 in the above example.