Exemple d'implémentation d'un filtre médian sur une image avec du buit avec python
from scipy import misc
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
#M = mpimg.imread('lena.png')
M = mpimg.imread('lena_grayscale.png')
print M.shape, type(M)
print M
salt_value = 40
noise = np.random.randint(salt_value+1, size=(512, 512))
#---------- Add Noise ----------#
indexe = np.where(noise == 0)
A = indexe[0]
B = indexe[1]
M[A,B,0] = 0.0
M[A,B,1] = 0.0
M[A,B,2] = 0.0
#---------- Plot & Save ----------#
print M.shape
my_dpi=100
fig = plt.figure(figsize=(800/my_dpi, 800/my_dpi), dpi=my_dpi)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
plt.imshow(M)
plt.title("Noisy Lena Image")
plt.savefig("lena_noisy_NoAxis.png", dpi=my_dpi)
plt.show()
plt.imshow(M)
plt.title("Noisy Lena Image")
plt.savefig("lena_noisy.png",bbox_inches='tight')
#---------- Median Filter ----------#
shape = M.shape
n_pixel = np.zeros((9))
for i in range(shape[0]-1):
for j in range(shape[1]-1):
if j > 0 and i > 0:
n_pixel[0] = M[i-1,j-1,0]
n_pixel[1] = M[i-1,j,0]
n_pixel[2] = M[i-1,j+1,0]
n_pixel[3] = M[i,j-1,0]
n_pixel[4] = M[i,j,0]
n_pixel[5] = M[i,j+1,0]
n_pixel[6] = M[i+1,j-1,0]
n_pixel[7] = M[i+1,j,0]
n_pixel[8] = M[i+1,j+1,0]
s = np.sort(n_pixel, axis=None)
M[i,j,0] = s[4]
M[i,j,1] = s[4]
M[i,j,2] = s[4]
plt.imshow(M)
plt.title("Median Filter")
plt.savefig("MedianFilterLena.png",bbox_inches='tight')
plt.show()
Recherches associées
Liens | Site |
---|---|
Filtre médian | wikipedia |