python噪声

1.skimage的API

 

noise_gs_img = util.random_noise(img,mode='gaussian') # gaussian 高斯加性噪声。
noise_salt_img = util.random_noise(img,mode='salt')#盐噪声,随机用1替换像素。属于高灰度噪声。
noise_pepper_img = util.random_noise(img,mode='pepper')# 胡椒噪声,随机用0或-1替换像素,属于低灰度噪声
noise_sp_img = util.random_noise(img,mode='s&p') # 椒盐噪声,两种噪声同时出现,呈现出黑白杂点
noise_speckle_img = util.random_noise(img,mode='speckle')# out = image + n *图像的乘法噪声,其中n是具有指定均值和方差的均匀噪声。
 

低层代码:

可以改变默认值字典中的数进行不同情况的噪声的演示

def img_as_float(image, force_copy=False):
        return _convert(image, np.floating, force_copy) #复制数值,转为浮点型

 

def random_noise(image, mode='gaussian', seed=None, clip=True, **kwargs):
    allowedtypes = {
        'gaussian': 'gaussian_values',
        'localvar': 'localvar_values',
        'poisson': 'poisson_values',
        'salt': 'sp_values',
        'pepper': 'sp_values',
        's&p': 's&p_values',
        'speckle': 'gaussian_values'}  #建立噪声字典

    kwdefaults = {
        'mean': 0.,
        'var': 0.01,
        'amount': 0.05,
        'salt_vs_pepper': 0.5,
        'local_vars': np.zeros_like(image) + 0.01}  #设置默认值

    allowedkwargs = {
        'gaussian_values': ['mean', 'var'],
        'localvar_values': ['local_vars'],
        'sp_values': ['amount'],
        's&p_values': ['amount', 'salt_vs_pepper'],
        'poisson_values': []}     #每个噪声获得的值

    for key in kwargs:   #关键字参数
        if key not in allowedkwargs[allowedtypes[mode]]:
            raise ValueError('%s keyword not in allowed keywords %s' %
                             (key, allowedkwargs[allowedtypes[mode]]))

    # Set kwarg defaults

    for kw in allowedkwargs[allowedtypes[mode]]:
        kwargs.setdefault(kw, kwdefaults[kw])   #kwarges如果提供则使用提供值

    if mode == 'gaussian':   #高斯函数   均值        标准差 
        noise = np.random.normal(kwargs['mean'], kwargs['var'] ** 0.5,
                                 image.shape)
        out = image + noise

    elif mode == 'localvar':   #局部高斯噪声
        # Ensure local variance input is correct
        if (kwargs['local_vars'] <= 0).any():
            raise ValueError('All values of `local_vars` must be > 0.')

        # Safe shortcut usage broadcasts kwargs['local_vars'] as a ufunc
        out = image + np.random.normal(0, kwargs['local_vars'] ** 0.5)

    elif mode == 'poisson':  #泊松分布
        # Determine unique values in image & calculate the next power of two
        vals = len(np.unique(image))
        vals = 2 ** np.ceil(np.log2(vals))

        # Ensure image is exclusively positive
        if low_clip == -1.:
            old_max = image.max()
            image = (image + 1.) / (old_max + 1.)

        # Generating noise for each unique value in image.
        out = np.random.poisson(image * vals) / float(vals)

        # Return image to original range if input was signed
        if low_clip == -1.:
            out = out * (old_max + 1.) - 1.

    elif mode == 'salt': 盐
        # Re-call function with mode='s&p' and p=1 (all salt noise)
        out = random_noise(image, mode='s&p', seed=seed,
                           amount=kwargs['amount'], salt_vs_pepper=1.)

    elif mode == 'pepper': 椒
        # Re-call function with mode='s&p' and p=1 (all pepper noise)
        out = random_noise(image, mode='s&p', seed=seed,
                           amount=kwargs['amount'], salt_vs_pepper=0.)

    elif mode == 's&p':  椒盐
        out = image.copy()
        p = kwargs['amount']
        q = kwargs['salt_vs_pepper']
        flipped = np.random.choice([True, False], size=image.shape,
                                   p=[p, 1 - p])
        salted = np.random.choice([True, False], size=image.shape,
                                  p=[q, 1 - q])
        peppered = ~salted
        out[flipped & salted] = 1
        out[flipped & peppered] = low_clip

    elif mode == 'speckle':
        noise = np.random.normal(kwargs['mean'], kwargs['var'] ** 0.5,
                                 image.shape)
        out = image + image * noise

高斯噪声是指噪声的概率密度函数服从高斯分布,白噪声是指噪声的任意两个采样样本之间不相关

Skimage读取图像是RGB,Skimage读取图像后是(height, width, channel)

而Opencv是BGR

 2.自定义:

def s_p_noise(image, proportion = 0.05):  #椒盐噪声
    noise_img= image
    height , width = noise_img.shape[0], noise_img.shape[1]  #这里用skimage的os读取,h w c (rgb),不同的读取方式这里需要改变
    num = int(height*width*proportion)   #有几个点被噪声污染
    for i in range(num):
        w=random.randint(0, width-1)
        h=random.randint(0, height-1)
        if random.randint(0, 1)==0:
            noise_img[h][w]=0
        else:
            noise_img[h][w]=255
    return noise_img
def Myguassian_noise(image,sigma=50,mean=0):  #高斯噪声
    img = image.astype(np.int16)  # 此步是为了避免像素点小于0,大于255的情况
    mean = mean
    sigma = sigma
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            for k in range(img.shape[2]):
                img[i, j, k] = img[i, j, k] + random.gauss(mu=mean, sigma=sigma)
    img= img.clip(0, 255)
    img = img.astype(np.uint8)

    return img
 img = io.imread("1.jpg")
    print(img.shape)
    noise_img = salt_and_pepper_noise(img)
    guassian_img = Myguassian_noise(img)
    io.imshow(noise_img)
    io.show()
    io.imshow(guassian_img)
    io.show()

椒盐噪声:

 

 

高斯噪声:
 

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值