Python-给图像添加椒盐噪声和高斯噪声

2021/6/10 14:22:45

本文主要是介绍Python-给图像添加椒盐噪声和高斯噪声,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

椒盐噪声和高斯噪声

在噪声的概念中,通常采用信噪比(Signal-Noise Rate, SNR)衡量图像噪声。通俗的讲就是信号占多少,噪声占多少,SNR越小,噪声占比越大。

在信号系统中,计量单位为dB,为10lg(PS/PN), PS和PN分别代表信号和噪声的有效功率。在这里,采用信号像素点的占比充当SNR,以衡量所添加噪声的多少。

椒盐噪声又称为脉冲噪声,它是一种随机出现的白点(盐噪声)或者黑点(椒噪声)。

高斯噪声是指它的概率密度函数服从高斯分布(即正态分布)的一类噪声。

原图:
image

代码:

import cv2
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
import random

def gasuss_noise(image, mean=0, var=0.001):
    '''
        添加高斯噪声
        mean : 均值
        var : 方差
    '''
    image = np.array(image/255, dtype=float)
    noise = np.random.normal(mean, var ** 0.5, image.shape)
    out = image + noise
    if out.min() < 0:
        low_clip = -1.
    else:
        low_clip = 0.
    out = np.clip(out, low_clip, 1.0)
    out = np.uint8(out*255)
    return out

def sp_noise(image,prob):
    '''
    添加椒盐噪声
    prob:噪声比例
    '''
    output = np.zeros(image.shape,np.uint8)
    thres = 1 - prob
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            rdn = random.random()
            if rdn < prob:
                output[i][j] = 0
            elif rdn > thres:
                output[i][j] = 255
            else:
                output[i][j] = image[i][j]
    return output

img = cv2.imread("1.jpg")
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# 添加椒盐噪声,噪声比例为 0.02
out1 = sp_noise(img, prob=0.02)
# 添加高斯噪声,均值为0,方差为0.009
out2 = gasuss_noise(img, mean=0, var=0.009)
cv2.imshow('out1',out1)
cv2.imwrite('sp.png',out1)
cv2.imshow('out2',out2)
cv2.imwrite('gasuss.png',out2)
cv2.waitKey(0)
cv2.destroyAllWindows()

实验结果

高斯(gasuss)
image
椒盐(sp)
image



这篇关于Python-给图像添加椒盐噪声和高斯噪声的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程