使用OpenCV产生脉冲,高斯以及盐和胡椒粉噪声
image-processing
opencv
11
0

我正在研究著名的Gonzales的“数字图像处理”上的图像处理,并谈论图像恢复,其中有许多示例是使用计算机生成的噪声(高斯,盐和胡椒粉等)完成的。在MATLAB中,有一些内置函数可以做到这一点。那OpenCV呢?

参考资料:
Stack Overflow
收藏
评论
共 5 个回答
高赞 时间 活跃

据我所知,没有像Matlab这样方便的内置函数。但是只需几行代码,您就可以自己创建这些图像。

例如加性高斯噪声:

Mat gaussian_noise = img.clone();
randn(gaussian_noise,128,30);

盐和胡椒粉噪音:

Mat saltpepper_noise = Mat::zeros(img.rows, img.cols,CV_8U);
randu(saltpepper_noise,0,255);

Mat black = saltpepper_noise < 30;
Mat white = saltpepper_noise > 225;

Mat saltpepper_img = img.clone();
saltpepper_img.setTo(255,white);
saltpepper_img.setTo(0,black);
收藏
评论

scikit-image包中有函数random_noise() 。它具有多种内置噪声模式,例如gaussians&p (用于盐和胡椒噪声), possionspeckle

下面我显示了如何使用此方法的示例

from PIL import Image
import numpy as np
from skimage.util import random_noise

im = Image.open("test.jpg")
# convert PIL Image to ndarray
im_arr = np.asarray(im)

# random_noise() method will convert image in [0, 255] to [0, 1.0],
# inherently it use np.random.normal() to create normal distribution
# and adds the generated noised back to image
noise_img = random_noise(im_arr, mode='gaussian', var=0.05**2)
noise_img = (255*noise_img).astype(np.uint8)

img = Image.fromarray(noise_img)
img.show()

在此处输入图片说明

还有一个名为imgaug的软件包,专用于以各种方式增强图像。它提供高斯,泊桑和盐和胡椒粉噪声增强剂。这是使用它为图像添加噪点的方法:

from PIL import Image
import numpy as np
from imgaug import augmenters as iaa


def main():
    im = Image.open("bg_img.jpg")
    im_arr = np.asarray(im)

    # gaussian noise
    # aug = iaa.AdditiveGaussianNoise(loc=0, scale=0.1*255)

    # poisson noise
    # aug = iaa.AdditivePoissonNoise(lam=10.0, per_channel=True)

    # salt and pepper noise
    aug = iaa.SaltAndPepper(p=0.05)

    im_arr = aug.augment_image(im_arr)

    im = Image.fromarray(im_arr).convert('RGB')
    im.show()


if __name__ == "__main__":
    main()
收藏
评论

简单的功能,可将高斯,椒盐斑纹和泊松噪声添加到图像

Parameters
----------
image : ndarray
    Input image data. Will be converted to float.
mode : str
    One of the following strings, selecting the type of noise to add:

    'gauss'     Gaussian-distributed additive noise.
    'poisson'   Poisson-distributed noise generated from the data.
    's&p'       Replaces random pixels with 0 or 1.
    'speckle'   Multiplicative noise using out = image + n*image,where
                n,is uniform noise with specified mean & variance.

import numpy as np
import os
import cv2

def noisy(noise_typ,image):

if noise_typ == "gauss":
        row,col,ch= image.shape
        mean = 0
        #var = 0.1
       #sigma = var**0.5
        gauss = np.random.normal(mean,1,(row,col,ch))
        gauss = gauss.reshape(row,col,ch)
        noisy = image + gauss
        return noisy
    elif noise_typ == "s&p":
        row,col,ch = image.shape
        s_vs_p = 0.5
        amount = 0.004
        out = image
        # Salt mode
        num_salt = np.ceil(amount * image.size * s_vs_p)
        coords = [np.random.randint(0, i - 1, int(num_salt))
                  for i in image.shape]
        out[coords] = 1

        # Pepper mode
        num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
        coords = [np.random.randint(0, i - 1, int(num_pepper))
                  for i in image.shape]
        out[coords] = 0
        return out
    elif noise_typ == "poisson":
        vals = len(np.unique(image))
        vals = 2 ** np.ceil(np.log2(vals))
        noisy = np.random.poisson(image * vals) / float(vals)
        return noisy
    elif noise_typ =="speckle":
        row,col,ch = image.shape
        gauss = np.random.randn(row,col,ch)
        gauss = gauss.reshape(row,col,ch)        
        noisy = image + image * gauss
        return noisy
收藏
评论

使用NumPy矩阵运算可以非常简单地添加“盐和胡椒”噪声。

def add_salt_and_pepper(gb, prob):
    '''Adds "Salt & Pepper" noise to an image.
    gb: should be one-channel image with pixels in [0, 1] range
    prob: probability (threshold) that controls level of noise'''

    rnd = np.random.rand(gb.shape[0], gb.shape[1])
    noisy = gb.copy()
    noisy[rnd < prob] = 0
    noisy[rnd > 1 - prob] = 1
    return noisy
收藏
评论
# Adding noise to the image    

import cv2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

img = cv2.imread('./fruit.png',0)
im = np.zeros(img.shape, np.uint8) # do not use original image it overwrites the image
mean = 0
sigma = 10
cv2.randn(im,mean,sigma) # create the random distribution
Fruit_Noise = cv2.add(img, im) # add the noise to the original image
plt.imshow(Fruit_Noise, cmap='gray')

可以更改均值和西格玛的值,以实现特定的噪声变化,例如高斯噪声或胡椒盐噪声等。您可以根据需要使用randn或randu。看一下文档: https : //docs.opencv.org/2.4/modules/core/doc/operations_on_arrays.html#cv2.randu

收藏
评论
新手导航
  • 社区规范
  • 提出问题
  • 进行投票
  • 个人资料
  • 优化问题
  • 回答问题

关于我们

常见问题

内容许可

联系我们

@2020 AskGo
京ICP备20001863号