为了消除图像的噪声,在制作的输入data和label的时候,在data中模拟图片或视频中常见的噪声 这样神经网络就可以更好的学习和更新参数,但是有些参数还需要根据具体场景,不断调整

代码如下:

import cv2
import numpy as np
 def noisy(noise_typ, image):
    if noise_typ == "gauss":
        # mean: 均值
        # var: 方差
        row, col, ch = image.shape
        mean = 0
        var = 0.01
        sigma = var ** 0.5
        noise = np.random.normal(mean, sigma, image.shape)
        out = image + noise
        if out.min() < 0:
            low_clip = 0.
        else:
            low_clip = out.min()
        out = np.clip(out, low_clip, 1.0)
        out = np.uint8(out * 255)
        cv2.imwrite('gauss.jpg', out)

        return out
    elif noise_typ == "SaltPepper":
        # row, col, ch = image.shape
        s_vs_p = 0.5
        amount = 0.004
        out = np.copy(image)
        # Salt
        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[coords] = 1

        # Pepper
        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[coords] = 0
        out = (out * 255).astype('uint8')
        cv2.imwrite('SaltPepper.jpg', out)
        return out

    elif noise_typ == "poisson":
        vals = len(np.unique(image))
        vals = 2 ** np.ceil(np.log2(vals))
        out = np.random.poisson(image * vals) / float(vals)

        out = (out * 255).astype('uint8')
        cv2.imwrite('poisson.jpg', out)
        return out
    elif noise_typ == "speckle":
        row, col, ch = image.shape
        gauss = np.random.randn(row, col, ch)
        # gauss = gauss.reshape(row, col, ch)
        out = image + image * gauss

        out = (out * 255).astype('uint8')
        return out


if __name__ == '__main__':
    img = cv2.imread('d.jpg')
    #归一化
    img = np.array(img / 255, dtype=float)
    noisy('gauss', img)
    noisy('SaltPepper', img)
    noisy('poisson', img)
    noisy('speckle', img)

原图

d

高斯噪声

gauss

椒盐噪声

SaltPepper

泊松噪声

poisson

散斑噪声

speckle

本文链接:http://nix.pub/article/makenoise/