Hi, I'm Ramu. This time, we will implement a median filter that removes noise in the image.
A median filter is a filter that smoothes and removes noise from images. By applying this filter, you can make the entire image look blurry.
This filter replaces the pixel of interest with the median of the surrounding pixels.
Also, as in the previous time, since the edge part of the image cannot be filtered, 0 padding processing using 0 is performed for pixels that do not exist.
import numpy as np import cv2 import matplotlib.pyplot as plt def medianFilter(img,k): w,h,c = img.shape size = k // 2 #0 padding process _img = np.zeros((w+2*size,h+2*size,c), dtype=np.float) _img[size:size+w,size:size+h] = img.copy().astype(np.float) dst = _img.copy() #Filtering process for x in range(w): for y in range(h): for z in range(c): dst[x+size,y+size,z] = np.median(_img[x:x+k,y:y+k,z]) dst = dst[size:size+w,size:size+h].astype(np.uint8) return dst #Image reading img = cv2.imread('image.jpg') #Median filter #Second argument: Filter size img = medianFilter(img,15) #Save image cv2.imwrite('result.jpg', img) #Image display plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) plt.show()
The left image is the input image, the center of the image is the output image by the previous Gaussian filter, and the right image is the current output image. You can see that the median filter can remove the point noise cleanly. It's not a very good comparison because the arguments are different, but the median filter can remove the point noise more cleanly.
If you have any questions, please feel free to contact us. imori_imori's Github has the official answer, so please check that as well. .. Also, since python is a beginner, please kindly point out any mistakes.