1. 程式人生 > 實用技巧 >OpenCV - Add Noise的一些方法

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