數字圖像處理:圖像加噪與復原

要求

對一副圖像加噪,進行幾何均值,算術均值,諧波,逆諧波處理

待處理圖像:

在這裏插入圖片描述
加噪聲函數:

def add_gaussian_noise(image_in, noise_sigma=25):
    temp_image = np.float64(np.copy(image_in))

    h = temp_image.shape[0]
    w = temp_image.shape[1]
    noise = np.random.randn(h, w) * noise_sigma

    noisy_image = np.zeros(temp_image.shape, np.float64)
    if len(temp_image.shape) == 2:
        noisy_image = temp_image + noise
    else:
        noisy_image[:, :, 0] = temp_image[:, :, 0] + noise
        noisy_image[:, :, 1] = temp_image[:, :, 1] + noise
        noisy_image[:, :, 2] = temp_image[:, :, 2] + noise
    """
    print('min,max = ', np.min(noisy_image), np.max(noisy_image))
    print('type = ', type(noisy_image[0][0][0]))
    """
    return noisy_image

def sp_noisy(image, s_vs_p=0.5, amount=0.08):
    out = np.copy(image)
    num_salt = np.ceil(amount * image.size * s_vs_p)
    coords = [np.random.randint(0, i - 1, int(num_salt)) for i in image.shape]
    out[tuple(coords)] = 255
    num_pepper = np.ceil(amount * image.size * (1. - s_vs_p))
    coords = [np.random.randint(0, i - 1, int(num_pepper)) for i in image.shape]
    out[tuple(coords)] = 0
    return out

噪聲圖

高斯噪聲:
在這裏插入圖片描述
鹽噪聲:
在這裏插入圖片描述
胡椒噪聲:
在這裏插入圖片描述

濾波函數

def filter(image, op):
    new_image = np.zeros(image.shape)
    image = cv2.copyMakeBorder(image, 1, 1, 1, 1, cv2.BORDER_DEFAULT)
    for i in range(1, image.shape[0] - 1):
        for j in range(1, image.shape[1] - 1):
            new_image[i - 1, j - 1] = op(image[i - 1:i + 2, j - 1:j + 2])
    new_image = (new_image - np.min(image)) * (255 / np.max(image))
    return new_image.astype(np.uint8)

幾何均值濾波器

幾何均值可由如下模板進行卷積求得,第三次作業已求過

k1 = np.array([
    [1, 1, 1],
    [1, 1, 1],
    [1, 1, 1]
], np.float32)/9

算術均值濾波器

操作函數:

def GeometricMeanOperator(roi):
    roi = roi.astype(np.float64)
    p = np.prod(roi)
    re = p ** (1 / (roi.shape[0] * roi.shape[1]))
    if re < 0:
        re = 0
    if re > 255:
        re = 255
    return re

效果

高斯:
在這裏插入圖片描述
鹽噪聲:
在這裏插入圖片描述
胡椒噪聲
在這裏插入圖片描述
幾何均值不適用於胡椒噪聲

諧波均值濾波器

操作函數:

def HMeanOperator(roi):
    roi = roi.astype(np.float64)
    re = roi.shape[0] * roi.shape[1] / np.sum([1/(p+0.0001) for p in roi])
    if re < 0:
        re = 0
    if re > 255:
        re = 255
    return re

效果

高斯:
在這裏插入圖片描述
鹽噪聲:
在這裏插入圖片描述
胡椒噪聲:
在這裏插入圖片描述
諧波均值也不適用於胡椒噪聲

逆諧波均值濾波器

操作函數:

def IHMeanOperator(roi, q):
    roi = roi.astype(np.float64)
    return np.mean(roi ** (q + 1)) / np.mean(roi ** q)


def IHMeanAlogrithm(image, q):
    new_image = np.zeros(image.shape)
    image = cv2.copyMakeBorder(image, 1, 1, 1, 1, cv2.BORDER_DEFAULT)
    for i in range(1, image.shape[0] - 1):
        for j in range(1, image.shape[1] - 1):
            new_image[i - 1, j - 1] = IHMeanOperator(image[i - 1:i + 2, j - 1:j + 2], q)
    new_image = (new_image - np.min(image)) * (255 / np.max(image))
    return new_image.astype(np.uint8)

效果

q>0時消除胡椒噪聲:
在這裏插入圖片描述
q<0時消除鹽噪聲:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章