OpenCV的脉冲,高斯和盐和胡椒噪音

时间:2013-01-21 09:23:53

标签: image-processing opencv

我正在研究着名的Gonzales "Digital Image Processing"上的图像处理,并谈论图像恢复,很多例子都是用计算机生成的噪声(高斯,盐和胡椒等)完成的。在MATLAB中有一些内置函数可以做到这一点。那么OpenCV呢?

9 个答案:

答案 0 :(得分:29)

据我所知,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);

答案 1 :(得分:11)

  

将高斯,椒盐斑点和泊松噪声添加到图像的简单函数

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

答案 2 :(得分:5)

“Salt&amp; Pepper”噪音可以使用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

答案 3 :(得分:4)

scikit-image包中包含函数random_noise()。它具有多种内置噪声模式,例如{if}gaussian(用于盐和胡椒噪声),s&ppossion

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

speckle

enter image description here

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

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()

答案 4 :(得分:2)

# 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。请查看文档:{​​{3}}

答案 5 :(得分:0)

#Adding noise
[m,n]=img.shape
saltpepper_noise=zeros((m, n));
saltpepper_noise=rand(m,n); #creates a uniform random variable from 0 to 1 
for i in range(0,m):
    for j in range(0,n):
        if saltpepper_noise[i,j]<=0.5:
            saltpepper_noise[i,j]=0
        else:
            saltpepper_noise[i,j]=255

答案 6 :(得分:0)

  

虽然没有像matlab那样的内置函数   &#34; imnoise(图像,noiseType,NoiseLevel)&#34;但我们可以随意轻松添加所需的金额   有价值的脉冲噪音或盐和胡椒手动进入图像。   1.增加随机值脉冲噪声。

import random as r
def addRvinGray(image,n): # add random valued impulse noise in grayscale 
    '''parameters: 
            image: type=numpy array. input image in which you want add noise.
            n:  noise level (in percentage)'''
    k=0                  # counter variable 
    ih=image.shape[0]    
    iw=image.shape[1]
    noisypixels=(ih*iw*n)/100      # here we calculate the number of pixels to be altered.

    for i in range(ih*iw):
        if k<noisypixels:
                image[r.randrange(0,ih)][r.randrange(0,iw)]=r.randrange(0,256) #access random pixel in the image gives random intensity (0-255)              
            k+=1
        else:
            break
    return image
  
      
  1. 添加盐和胡椒的噪音
  2.   
def addSaltGray(image,n): #add salt-&-pepper noise in grayscale image

    k=0
    salt=True
    ih=image.shape[0]
    iw=image.shape[1]
    noisypixels=(ih*iw*n)/100

    for i in range(ih*iw):
            if k<noisypixels:  #keep track of noise level
                if salt==True:
                        image[r.randrange(0,ih)][r.randrange(0,iw)]=255
                        salt=False
                else:
                        image[r.randrange(0,ih)][r.randrange(0,iw)]=0
                        salt=True
                k+=1
            else:
                break
    return image
  

&#39;&#39;&#39;注意:对于彩色图像:首先将图像分割为三个或四个通道        取决于使用opencv函数的输入图像:        (B,G,R)= cv2.split(图像)
       (B,G,R,A)= cv2.split(图像)
      分割后在所有通道上执行相同的操作。       最后合并所有渠道:            merged = cv2.merge([B,G,R])            返回合并&#39;&#39;&#39;&#39;   我希望这会对某人有所帮助。

答案 7 :(得分:0)

http://scikit-image.org/docs/dev/api/skimage.util.html#skimage.util.random_noise

skimage.util.random_noise(image, mode='gaussian', seed=None, clip=True, **kwargs)

答案 8 :(得分:0)

我对@Shubham Pachori的代码做了一些更改。当将图像读取为numpy阵列时,默认的dtype为uint8,当在图像上添加噪点时可能会导致换行。

import numpy as np
from PIL import Image

"""
image: read through PIL.Image.open('path')
sigma: variance of gaussian noise
factor: the bigger this value is, the more noisy is the poisson_noised image

##IMPORTANT: when reading a image into numpy arrary, the default dtype is uint8,
which can cause wrapping when adding noise onto the image. 
E.g,  example = np.array([128,240,255], dtype='uint8')
     example + 50 = np.array([178,44,49], dtype='uint8')
Transfer np.array to dtype='int16' can solve this problem.
"""


def gaussian_noise(image, sigma):
    img = np.array(image)
    noise = np.random.randn(img.shape[0], img.shape[1], img.shape[2])
    img = img.astype('int16')
    img_noise = img + noise * sigma
    img_noise = np.clip(img_noise, 0, 255)
    img_noise = img_noise.astype('uint8')
    return Image.fromarray(img_noise)


def poisson_noise(image, factor):
    factor = 1 / factor
    img = np.array(image)
    img = img.astype('int16')
    img_noise = np.random.poisson(img * factor) / float(factor)
    np.clip(img_noise, 0, 255, img_noise)
    img_noise = img_noise.astype('uint8')
    return Image.fromarray(img_noise)