UOMOP

New : add noise to image using Norm2 본문

Wireless Comm./Python

New : add noise to image using Norm2

Happy PinGu 2023. 5. 30. 20:05
def add_noise(signal, snr_db):
    ''' 
    signal: np.ndarray
    snr: float

    returns -> np.ndarray
    '''
    if type(signal[0][0]) != "numpy.float64" :
        signal = signal.astype(float)
        
    sig_flattend = signal.flatten().tolist()
    Norm2 = np.linalg.norm(sig_flattend, axis = 0, ord = 2)
    signal *= signal * Norm2

    snr = 10.0 ** (snr_db / 10.0)
    # Generate the noise as you did
    noise = acoustics.generator.white(signal.size).reshape(*signal.shape)
    # For the record I think np.random.random does exactly the same thing

    # work out the current SNR
    current_snr = np.mean(signal) / np.std(noise)

    # scale the noise by the snr ratios (smaller noise <=> larger snr)
    noise *= (current_snr / snr)

    # return the new signal with noise
    return signal + noise
img = cv2.imread("/content/lena.png", cv2.IMREAD_GRAYSCALE)
plt.imshow(img, cmap = "gray")

img_noise = add_noise(img, 1)
plt.imshow(img_noise, cmap = "gray")

img_noise = add_noise(img, 10)
plt.imshow(img_noise, cmap = "gray")

Comments