均值滤波和中值滤波

均值滤波:

利用卷积核kernel来实现像素均值的操作,通过这种操作来实现降噪

中值滤波:

和均值差不多,只是实现的方法变成了去中值

​
import cv2 as cv
import numpy as np
'''
    均值模糊 中值模糊 自定义模糊
'''


def blur_demo(image):
    dst = cv.blur(image, (2, 1))
    cv.imshow("blur_demo", dst)


def median_blur_demo(image):
    dst = cv.medianBlur(image, 5)
    cv.imshow("median_demo", dst)


def custom_blur_demo(image):
    kernel = np.ones([5, 5], np.float32)/25
    kernel_new = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32)  # 算子自定义取值 : 奇数 总和为1 or 0 1:做边缘梯度 0: 做增强
    dst = cv.filter2D(image, -1, kernel=kernel_new)
    cv.imshow("custom_blur_demo", dst)


def noise(image, snr):
    h, w = image.shape[:2]
    image_copy = image.copy()
    sp = h*w
    NP = int(sp*(1-snr))
    for i in range(NP):
        randx = np.random.randint(1, h-1)
        randy = np.random.randint(1, w-1)
        if np.random.random() <= 0.5:
            image_copy[randx, randy] = 0
        else:
            image_copy[randx, randy] = 255
    return image_copy


cv.namedWindow("lena", cv.WINDOW_AUTOSIZE)
src = cv.imread("D:/Pic/PS/lena.png")
src_noise = noise(src, 0.9)
# blur_demo(src)
median_blur_demo(src_noise)
custom_blur_demo(src_noise)
blur_demo(src_noise)
cv.imshow("lena", src)
cv.imshow("lena_noise", src_noise)
cv.waitKey(0)
cv.destroyAllWindows()

​

均值滤波和中值滤波_第1张图片

你可能感兴趣的:(图像处理)