适度增加高斯噪声和椒盐噪声可以提高模型的泛化能力
高斯噪声:
import numpy as np
def gaussian_noise(image, mean=0.1, sigma=0.1):
"""
:param image:原图
:param mean:均值
:param sigma:标准差 值越大,噪声越多
"""
image = np.asarray(image / 255, dtype=np.float32)
noise = np.random.normal(mean, sigma, image.shape).astype(dtype=np.float32) # 产生高斯噪声
output = image + noise # 将噪声和图片叠加
output = np.clip(output, 0, 1)
output = np.uint8(output * 255)
return output
椒盐噪声
import numpy as np
def add_salt_pepper_noise(image: np.ndarray, prob=0.02):
"""
:param image:图像
:param prob: 椒盐噪声噪声比例
prob * 0.51 用于添加盐噪声;
prob * 0.5 用于添加胡椒噪声
希望盐的概率稍微比胡椒的概率略高。
"""
image = add_uniform_noise(image, prob * 0.51, vaule=255)
image = add_uniform_noise(image, prob * 0.5, vaule=0)
return image
def add_uniform_noise(image: np.ndarray, prob=0.05, vaule=255):
"""
随机生成一个0~1的mask,作为椒盐噪声
:param image:图像
:param prob: 噪声比例
:param vaule: 噪声值
:return:
"""
h, w = image.shape[:2]
noise = np.random.uniform(low=0.0, high=1.0, size=(h, w)).astype(dtype=np.float32) # 产生高斯噪声
mask = np.zeros(shape=(h, w), dtype=np.uint8) + vaule #盐噪声mask填充为255,胡椒噪声填充为0
index = noise > prob ##确定添加噪声的位置
mask = mask * (~index)
output = image * index[:, :, np.newaxis] + mask[:, :, np.newaxis]
output = np.clip(output, 0, 255)
output = np.uint8(output)
return output