Fix #10: Implement Wiener filter

This commit is contained in:
Benjamin Loison 2024-03-21 15:11:15 +01:00
parent 739317fa63
commit f3e96243f3
Signed by: Benjamin_Loison
SSH Key Fingerprint: SHA256:BtnEgYTlHdOg1u+RmYcDE0mnfz1rhv5dSbQ2gyxW8B8

View File

@ -2,6 +2,7 @@
from PIL import Image
from statistics import mean, median
from tqdm import tqdm
# What about other color channels? See #11.
MODE = 'L'
@ -42,29 +43,38 @@ for m in range(1, IImage.size[0] - 1):
newPixel = I[m, n] - median(A)
r[m - 1, n - 1] = round(newPixel)
# Why need to rotate the image? See #14.
rImage.rotate(-90).show()
Q = 3
# $\sigma_0^2$ is the noise variance.
sigma_0 = sqrt(9)
sigma_0 = 9 ** 0.5
h_wImage = Image.new(MODE, (rImage.size[0], rImage.size[1]))
h_wImagePixels = h_wImage.load()
# Wiener filter.
def h_w(i, j):
def h_w(h, i, j):
# Equation (7)
return h[i, j] * sigma(i, j) / (sigma(i, j) + sigma_0 ** 2)
return h[i, j] * sigma(h, i, j) / (sigma(h, i, j) + sigma_0 ** 2)
# Minimum of the considered variances.
def sigma(i, j):
def sigma(h, i, j):
# Equation (9)
return sigma_q(i, j, Q)
return sigma_q(h, i, j, Q)
def getPixelIndexesAround(i, numberOfPixelsInEachDirection):
return range(i - numberOfPixelsInEachDirection, i + numberOfPixelsInEachDirection)
# Local variance obtained by Maximum A Posteriori (MAP).
def sigma_q(i, j, q):
def sigma_q(h, i, j, q):
# Equation (8)
numberOfPixelsInEachDirection = (q - 1) // 2
B_q = [(x, z) for x in getPixelIndexesAround(i, numberOfPixelsInEachDirection) for z in getPixelIndexesAround(j, numberOfPixelsInEachDirection)]
return max(0, (1 / q ** 2) * sum([h[x, z] ** 2 - sigma_0 ** 2 for (x, z) in B_q]))
# Why need to rotate the image? See #14.
rImage.rotate(-90).show()
for i in tqdm(range(rImage.size[0])):
for j in range(rImage.size[1]):
h_wImagePixels[i, j] = round(h_w(r, i, j))
h_wImage.rotate(-90).show()