I am trying to implement a weighted median filter in Python. It seems to color correct the whole image rather than filter the salt-and-pepper noise that I added to the original image.
import numpy as np
from skimage import io
from matplotlib import pyplot as plt
def add_zg_impuls(img, ratio):
H, W, ch = img.shape
length = int(H*W*ch*ratio)
lin = np.random.randint(0, H, length)
col = np.random.randint(0, W, length)
val = np.random.randint(0, 2, length)
img_impuls = img.copy()
for i in range(length):
img_impuls[lin[i], col[i], np.random.randint(0, 3)] = 255 * val[i]
return img_impuls
def apply_L_filter(img, size, weights):
h, w,c = img.shape
cap = size // 2
new_img = np.zeros_like(img)
for i in range(cap, h - cap):
for j in range(cap, w - cap):
for canal in range(c):
vec = img[i-cap:i+cap+1, j-cap:j+cap+1, canal]
values = np.reshape(vec, size*size)
sorted_values = np.sort(values)
weighted_values = sorted_values * weights.flatten()
new_img[i, j, canal] = np.sum(weighted_values)
return new_img
image = io.imread("tiffany.bmp")
plt.figure(), plt.imshow(image), plt.title("Imagine originala"), plt.show()
image_noise= add_zg_impuls(image,0.1)
plt.figure(), plt.imshow(image_noise), plt.title("Imagine alterata 10%"), plt.show()
filter_size = 5
filter_weights = np.array([[1, 1, 1, 1, 1], [1, 2, 2, 2, 1], [1, 2, 3, 2, 1], [1, 2, 2, 2, 1], [1, 1, 1, 1, 1]])
filtered_image = apply_L_filter(image_noise, filter_size, filter_weights)
plt.figure(), plt.imshow(filtered_image), plt.title("Imagine filtrata ponderat"), plt.show()
