1. 程式人生 > >產生正太隨機數的Box–Muller變換

產生正太隨機數的Box–Muller變換

為擴充訓練樣本、進行資料增廣,常用的方法之一是加(零均的)高斯噪聲

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

有圖有真相 原圖 高斯噪聲