OpenCV - Add Noise的一些方法

噪声常用有两种:一种椒盐噪声,一种高斯噪声。

import numpy as np


def pepper_and_salt(src, proportion):
    """
    :param src: the original image
    :param proportion: the proportion of salt and pepper noise
    :return:
    """
    noise_img = np.copy(src)
    noise_num = int(proportion * src.shape[0] * src.shape[1])

    for i in range(noise_num):
        rand_x = np.random.randint(0, src.shape[0]-1)
        rand_y = np.random.randint(0, src.shape[1]-1)

        if np.random.randint(0, 1) <= 0.5:
            noise_img[rand_x, rand_y] = 0
        else:
            noise_img[rand_x, rand_y] = 255
    return noise_img


def gaussian_noise(img, mean=0, var=0.001):
    """
    :param img: the original 
    :param mean: set mean
    :param var:  set var
    :return: 
    """
    noise_img = np.array(img / 255, dtype=float, copy=True)
    noise = np.random.normal(mean, var ** 0.5, noise_img.shape)
    out = noise_img + noise
    if out.min() < 0:
        low_clip = -1.
    else:
        low_clip = 0.
    out = np.clip(out, low_clip, 1.0)
    out = np.uint8(out * 255)
    return out

 

posted on 2020-12-04 21:00  Black_x  阅读(288)  评论(0编辑  收藏  举报