lwwwr lwwwr - 2 months ago 10
Python Question

Removing noise from image Python PIL

Newbie here.
Have an image
I added noise on image, and them i need to clear image with noise(or something like that).
The unnoising algorythm is next:


If the brightness of the pixel is greater than the average brightness
of the local neighborhood, then the brightness of the pixel is
replaced with the average brightness of the surroundings.


from PIL import Image
import random
from multiprocessing import Pool
from multiprocessing.dummy import Pool as ThreadPool

img=Image.open('pic.bmp')
print(img.size)
randomenter=int(input('Enter numpix: '))
for numpix in range(0, randomenter):
x=random.randint(0,int(img.size[0]-1))
y=random.randint(0,int(img.size[1]-1))
r=random.randint(0,255)
g=random.randint(0,255)
b=random.randint(0,255)
img.putpixel((x,y),(r,g,b))
img.show()
img.save("noise.bmp", "BMP")

img2=Image.open("noise.bmp")
w, h = img2.size

pix=img2.copy()
for x in range(0,w-1):
if x-1>0 and x<w:
for y in range(0,h-1):
if y-1>0 and y<h:
local1=(0.3 * pix.getpixel((x-1,y-1))[0]) + (0.59 * pix.getpixel((x-1,y-1))[1]) + (0.11 * pix.getpixel((x-1,y-1))[2])
local2=(0.3 * pix.getpixel((x-1,y))[0]) + (0.59 * pix.getpixel((x-1,y))[1]) + (0.11 * pix.getpixel((x-1,y))[2])
local3=(0.3 * pix.getpixel((x-1,y+1))[0]) + (0.59 * pix.getpixel((x-1,y+1))[1]) + (0.11 * pix.getpixel((x-1,y+1))[2])
local4=(0.3 * pix.getpixel((x,y-1))[0]) + (0.59 * pix.getpixel((x,y-1))[1]) + (0.11 * pix.getpixel((x,y-1))[2])
LOCAL5=(0.3 * pix.getpixel((x,y))[0]) + (0.59 * pix.getpixel((x,y))[1]) + (0.11 * pix.getpixel((x,y))[2])
local6=(0.3 * pix.getpixel((x,y+1))[0]) + (0.59 * pix.getpixel((x,y+1))[1]) + (0.11 * pix.getpixel((x,y+1))[2])
local7=(0.3 * pix.getpixel((x+1,y-1))[0]) + (0.59 * pix.getpixel((x+1,y-1))[1]) + (0.11 * pix.getpixel((x+1,y-1))[2])
local8=(0.3 * pix.getpixel((x+1,y))[0]) + (0.59 * pix.getpixel((x+1,y))[1]) + (0.11 * pix.getpixel((x+1,y))[2])
local9=(0.3 * pix.getpixel((x+1,y+1))[0]) + (0.59 * pix.getpixel((x+1,y+1))[1]) + (0.11 * pix.getpixel((x+1,y+1))[2])
localall=(local1+local2+local3+local4+local6+local7+local8+local9)/8
if LOCAL5<localall:
img2.putpixel((x,y),(int(pix.getpixel((x,y))[0]*localall/LOCAL5),int(pix.getpixel((x,y))[1]*localall/LOCAL5),int(pix.getpixel((x,y))[2]*localall/LOCAL5)))
img2.show()


There is a problem at the moment of the brightness changing.
Official docks have no detail information about this case.
Is there any solution?

Answer

First of all, you need to create a copy of your image to write your data to: imgCopy = img.copy(). Else, your noise corrected pixels will influence the correction of pixels not yet touched. In your else statement you simply have to normalize your middle pixel, then multiply it with the average brightness you calculated:

imgCopy[i, j] = imgCopy[i, j] * local / nuzh