在matlab中,存在执行直接得函数来添加高斯噪声和椒盐噪声。Python-OpenCV中虽然不存在直接得函数,但是很容易使用相关的函数来实现。
代码:
import numpy as np import random import cv2 def sp_noise(image,prob): ''' 添加椒盐噪声 prob:噪声比例 ''' output = np.zeros(image.shape,np.uint8) thres = 1 - prob for i in range(image.shape[0]): for j in range(image.shape[1]): rdn = random.random() if rdn < prob: output[i][j] = 0 elif rdn > thres: output[i][j] = 255 else: output[i][j] = image[i][j] return output def gasuss_noise(image, mean=0, var=0.001): ''' 添加高斯噪声 mean : 均值 var : 方差 ''' image = np.array(image/255, dtype=float) noise = np.random.normal(mean, var ** 0.5, image.shape) out = image + 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) #cv.imshow("gasuss", out) return out
可见,只要我们得到满足某个分布的多维数组,就能作为噪声添加到图片中。
例如:
import cv2 import numpy as np > im = np.empty((5,5), np.uint8) # needs preallocated input image > im array([[248, 168, 58, 2, 1], # uninitialized memory counts as random, too "htmlcode">img = ... noise = ... image = img + noise参考链接:
1、https://stackoverflow.com/questions/22937589/how-to-add-noise-gaussian-salt-and-pepper-etc-to-image-in-python-with-opencv#
2、https://stackoverflow.com/questions/14435632/impulse-gaussian-and-salt-and-pepper-noise-with-opencv#
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。