为扩充训练样本、进行数据增广,常用的方法之一是加(零均的)高斯噪声

1.高斯噪声的产生

计算机可以很方便地产生0-1均值分布,Box-Muller变换可以将该均值分布转换成正太分布:
两组独立的随机数U和V,这两组数在(0,1]上均匀分布,用U和V生成两组独立的标准常态分布随机变量X和Y:
X=2lnUcos(2πV)X=\sqrt{-2lnU}cos(2\pi V)
Y=2lnUcos(2πV)Y=\sqrt{-2lnU}cos(2\pi V)

2.代码

 # -*- coding: utf-8 -*- 
import cv2
import numpy as np
myimg=cv2.imread(‘test1.jpg’)#RGB格式


def val_limit(val,low,hig):#限制输出超过灰度集
    if val < low:
        new_val = 0
    elif val > hig:
        new_val = hig
    else:
        new_val = val
    return new_val

def noiseing(img):
    param = 30# 高斯分布的振幅
    grayscale = 255#灰度集(0-255)的最大值
    w = img.shape[1]
    h = img.shape[0]
    newimg = np.zeros((h, w, 3), np.uint8)
    for x in range(0, h):
        for y in range(0, w, 2):
            r1 = np.random.random_sample()
            r2 = np.random.random_sample()
            z1 = param * np.cos(2 * np.pi * r2) * np.sqrt((-2) * np.log(r1))
            z2 = param * np.sin(2 * np.pi * r2) * np.sqrt((-2) * np.log(r1))
            newimg[x, y, 0] = np.uint8(val_limit(int(img[x, y, 0] + z1), 0, grayscale))
            newimg[x, y, 1] = np.uint8(val_limit(int(img[x, y, 1] + z1), 0, grayscale))
            newimg[x, y, 2] = np.uint8(val_limit(int(img[x, y, 2] + z1), 0, grayscale))
            newimg[x, y+1, 0] = np.uint8(val_limit(int(img[x, y, 0] + z2), 0, grayscale))
            newimg[x, y+1, 1] = np.uint8(val_limit(int(img[x, y, 1] + z2), 0, grayscale))
            newimg[x, y+1, 2] = np.uint8(val_limit(int(img[x, y, 2] + z2), 0, grayscale))
    return newimg

有图有真相
产生正太随机数的Box–Muller变换
产生正太随机数的Box–Muller变换

相关文章:

  • 2021-06-30
  • 2021-06-12
  • 2021-10-11
  • 2021-09-15
猜你喜欢
  • 2021-11-01
  • 2022-02-22
  • 2022-12-23
  • 2021-07-29
  • 2021-04-11
  • 2022-12-23
相关资源
相似解决方案