Python用opencv处理图像自定义函数实现大小为7乘以7大小的均值滤波和中值滤波代码

具体要求如下:
使用胡椒盐噪音降低下面的图像。
b、在这一部分中,我们尝试使用两种不同的滤波器来恢复被胡椒盐噪声降解的图像。
b.1 内核大小为7 × 7的算术平均值过滤器(需要填写第46-56行)
b.2 核大小为7 × 7的中值
加了噪声后的图像:
概率是0.25的加噪声图像
进行滤波去噪后的图像:
左边是均值滤波图像,右边是中值滤波图像
图像还原后的图像:
第三张图为还原后的图像

"""
... are the places you need to fill
"""
import math
import numpy as np
import cv2
from matplotlib import pyplot as plt

######################################
#该过程是添加噪声的过程,255是salt;0是pepper
def salt_pepper_noise(img):
    """
    Degrade image using salt_pepper noise
    """
    h, w = img.shape

    p_salt = 0.25  # probability of salt noise
    p_pepper = 0.25
    p_noise = p_salt + p_pepper

    noisy_image = np.zeros_like(img)

    for i in range(h):
        for j in range(w):
            random_p = np.random.uniform(0, 1)
            if random_p > p_noise:
                noisy_image[i, j] = img[i, j]
            elif random_p < p_salt:
                noisy_image[i, j] = 255  # if true, add salt noise, maximum value = 255, minimum value = 0
            else:
                noisy_image[i, j] = 0  # add pepper noise, maximum value = 255, minimum value = 0

    plt.subplot(121), plt.imshow(img, cmap='gray')
    plt.title('Input Image'), plt.xticks([]), plt.yticks([])
    plt.subplot(122), plt.imshow(noisy_image, cmap='gray')
    plt.title('noisy_image'), plt.xticks([]), plt.yticks([])
    plt.show()
    return noisy_image
############################################################################

############################################################################
#这是均值滤波和中值滤波的过程,内核为(7,7)大小的模板
def mean_median_fliters(noisy_image):
    """
    mean filter, median filter
    """
    h, w = noisy_image.shape
    # mean filter
    k_mean = 7
    denoised_image_mean = np.zeros_like(noisy_image)
    # to avoid positions outside the image, we first pad the image using zeros.
    noisy_image_pad = np.zeros((h+k_mean-1, w+k_mean-1))
    noisy_image_pad[int((k_mean-1)/2): h+int((k_mean-1)/2), int((k_mean-1)/2): w+int((k_mean-1)/2)] = noisy_image
    for i in range(h):
        for j in range(w):
            ROI =  noisy_image[i,j] # select the region of interest (ROI), or the region belongs to a kernel.
            denoised_value = np.mean(ROI) # calculate the average value
            denoised_image_mean[i, j] =denoised_value


    # median filter
    k_median = 7
    denoised_image_median = np.zeros_like(noisy_image)
    # to avoid positions outside the image, we first pad the image with zeros.
    noisy_image_pad = np.zeros((h+k_median-1, w+k_median-1))
    noisy_image_pad[int((k_mean-1)/2): h+int((k_mean-1)/2), int((k_mean-1)/2): w+int((k_mean-1)/2)] = noisy_image
    for i in range(h):
        for j in range(w):
            ROI = noisy_image[i,j]  # select the region of interest (ROI), or the region belongs to a kernel.
            denoised_value = np.median(ROI)  # select the median value
            denoised_image_median[i, j] = denoised_value

    cv2.imwrite('mean_filter.png', np.uint8(denoised_image_mean))
    cv2.imwrite('median_filter.png', np.uint8(denoised_image_median))

    plt.subplot(131), plt.imshow(denoised_image_mean, cmap='gray')
    plt.title('mean filter'), plt.xticks([]), plt.yticks([])
    plt.subplot(132), plt.imshow(denoised_image_median, cmap='gray')
    plt.title('median filter'), plt.xticks([]), plt.yticks([])
    plt.show()
####################################################################################################

###############################################################################################
#该过程是使用自定义的模型进行图像的还原
def inverse_filtering(H_shift, img_blur):
    """
    Inverse filtering
    """

    cutoff_H = 40  # cutoff radius
    h, w = img_blur.shape
    h_c = h/2  # point center
    w_c = w/2

    # the observed image.
    G = cv2.dft(np.float32(img_blur), flags=cv2.DFT_COMPLEX_OUTPUT)
    G_shift = np.fft.fftshift(G)

    # cutoff H_shift, if distance > cutoff, do not change the frequency of observed image.
    for v in range(h):
        for u in range(w):
            distance = (v-h_c)**2 + (u-w_c)**2
            if distance > cutoff_H*cutoff_H:
                H_shift[v, u, :] = 1
                # H_shift[v, u, :] = 1e10 # alternatively, you can discard the frequency outside the cutoff radius by assigning H a very large value.

    f_shift = G_shift  # inverse filtering
    f_ishift = np.fft.ifftshift(f_shift)
    img_restored = cv2.idft(f_ishift, flags=cv2.DFT_SCALE | cv2.DFT_REAL_OUTPUT)
    img_restored = np.uint8(np.maximum(np.minimum(img_restored, 255), 0))
    cv2.imwrite('inverse_filtering.png', img_restored)

    plt.subplot(131), plt.imshow(img_blur, cmap='gray')
    plt.title('observed image'), plt.xticks([]), plt.yticks([])
    plt.subplot(132), plt.imshow(img_restored, cmap='gray')
    plt.title('restored image'), plt.xticks([]), plt.yticks([])
    plt.subplot(133), plt.imshow(img, cmap='gray')
    plt.title('reference image'), plt.xticks([]), plt.yticks([])
    plt.show()

#################################################################################################
#调用函数才能执行相应的过程

if __name__=='__main__':

    img = np.float32(cv2.imread('hku.png', 0))
    noisy_image = salt_pepper_noise(img)

    mean_median_fliters(img)

    H_shift = np.load('gaussian_low_pass.npy')  # low-pass gaussian filter (frequency domain), center is 1.
    img_blur = cv2.imread('blurry_hku.png', 0)

    inverse_filtering(H_shift, img_blur)

加了噪声后的图像:
概率是0.25的加噪声图像
进行滤波去噪后的图像:
左边是均值滤波图像,右边是中值滤波图像
图像还原后的图像:
第三张图为还原后的图像
今天的方享到此结束,希望对您有所帮助!!!

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值