from PIL import Image
from math import *
import numpy
list1 = []
im = Image.open("313.JPG")
im.show()
list1 = list(im.getdata())
length = len(list1)
# generate random noise data with mean 0 and sd 10
list2 = numpy.random.normal(0, 10, length)
# Add this to the image data
list3 = list1+list2
im.putdata(list3)
im.show()
Image getting dark
-
24-06-2023 - |
Вопрос
I did a program in python to apply Gaussian noise on an image as follows. Input image is :
from PIL import Image
from math import *
import numpy
list1 = []
list2 = []
im = Image.open("313.JPG")
im.show()
list1 = list(im.getdata())
length = len(list1)
total = 0
for i in list1:
total = total + i
mean = total /length #mean
sd = numpy.std(list1) #standard deviation
print "mean is %d" %(mean)
print "sd is %d" %(sd)
for i in list1:
g = (1/(sd * sqrt(2*pi)))*(exp(-((i - mean)**2)/(2*(sd**2)))) #gaussian
list2.append(g)
im.putdata(list2)
im.save('q4.jpg')
im.show()
But I am getting a complete dark image instead of getting noise on image.Please help.I'm expecting the below image as output.
Решение 2
Другие советы
Since gaussian is normalized, and its peak is in 1/sqrt(2pi)
, you should multiply g
for 255*sqrt(2*math.pi)
.
Since yout g
is not a normal gaussian, but it is also normalized by 1/sd
, to let g
span fro m0
to 255
you shoud moltiply g
by N
as follows:
N = 255.*sqrt(2.*pi)*sd
g = N*(1/(sd * sqrt(2*pi)))*(exp(-((i - mean)**2)/(2*(sd**2))))
This is what I get with your image as input:
It is correct: your algorithm just compute for every pixel, its gaussian value (where the gaussian is centered in the mean value): this means that pixel with a value near the average value will get brigher and pixel distant from the average get darker. No way to get a noise from that. You should re think your algorithm.