Mean filtering is a common means in image processing. From the point of view of frequency domain, mean filtering is a low-pass filter, and high-frequency signals will be removed. Mean filtering can help to eliminate sharp noise of images and realize the functions of image smoothing and blurring. The ideal average filtering is to replace each pixel in the image with the average value calculated by each pixel and its surrounding pixels.
Taking the 3*3 average filter as an example, the algorithm principle of the average filter is as follows:
2. Denoising the image polluted by salt and pepper noise with the average filter.
Python source code:
import cv2
import numpy as np
# mean filter
def mean_filter(img, K_size=3):
H, W, C = img.shape
# zero padding
pad = K_size // 2
out = np.zeros((H + pad * 2, W + pad * 2, C), dtype=np.float)
out[pad: pad + H, pad: pad + W] = img.copy().astype(np.float)
tmp = out.copy()
# filtering
for y in range(H):
for x in range(W):
for c in range(C):
out[pad + y, pad + x, c] = np.mean(tmp[y: y + K_size, x: x + K_size, c])
out = out[pad: pad + H, pad: pad + W].astype(np.uint8)
return out
# Read image
img = cv2.imread("../paojie_sp 1.jpg")
# Mean Filter
out = mean_filter(img, K_size=5)
# Save result
cv2.imwrite("out.jpg", out)
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
III. Experimental results:
It can be seen that the noise in the image is weakened, but the image becomes blurred after mean filtering. Because the average filter filters out the high-frequency components in the image, the edges of the image are blurred. (To remove a certain amount of salt and pepper noise, consider using median filtering.)
IV. Reference content:
blogs.com/wojianxin/p/ 1250 189 1.html