**How to add salt and pepper noise to an image**

To
obtain an image with ‘

**speckle**’ or ‘**salt and pepper**’ noise we need to add white and black pixels randomly in the image matrix.
First convert the RGB image into grayscale image.

Then generate random values for the size of the
matrix.

Here I used MATLAB function ‘randint’.

This function will generate random values for the
given matrix size within the specified range.

For instance, consider an image matrix of size 4X3

Imgmatrix =

237 107
166

234 95
162

239 116
169

56 126
89

Generate random values for a 4X3 matrix with range 0
to 10.

randint(4,3,[0,10])

ans =

4 10
4

7 8
4

10 0 5

3 10
9

Now we can replace with pixel value zero (black) in
the image matrix if there is ‘0’ value in the random matrix.

Now the image matrix will have black pixels.

Imgmatrix =

237 107
166

234 95
162

239 0 169

56 126
89

Similarly, replace the image matrix pixel value with
‘255’ if there is value ‘10’ in the random matrix.

The white pixels are now added.

Imgmatrix =

237 255 166

234 95
162

255 0 169

56 126
89

Black=0 white=255 |

MATLAB CODE:

A=imread('taj.jpg');

B=rgb2gray(A);

black=3;

white=253;

%Adjust the values in 'black' and 'white' to increase the noise.

NoiseImg = B;

Rmatrix =
randint(size(B,1),size(B,2),[0,255]);

NoiseImg(Rmatrix <= black) = 0;

NoiseImg(Rmatrix >=white) = 255;

RImg=medfilt2(NoiseImg);

figure,subplot(1,2,1),imshow(NoiseImg),title('Add ''Salt
and Pepper'' Noise');

subplot(1,2,2),imshow(RImg),title('After Noise
Removal');

I used the MATLAB function 'medfilt2' to remove noise.

## 7 comments:

how to add different percentage level of noise to an image

@Mukesh Mann

Try this code.

B=imread('eight.tif');

%if Pa==Pb;

percen=20;

%Noise level 20

Prob_den_f=255*percen/100;

NoiseImg = B;

Rmatrix = randint(size(B,1),size(B,2),[0,255]);

NoiseImg(Rmatrix <=Prob_den_f/2) = 0;

NoiseImg(Rmatrix >Prob_den_f/2&Rmatrix<Prob_den_f) = 255;

RImg=medfilt2(NoiseImg);

@Aaron Angelthanks a lot angel....can we apply the following code to add different noise to an inmage

let standard deviation 0.25

then

types of noise

1.noise_spekle=imnoise(image,'speckle',.25);

2. noise_gaussian=imnoise(image,'gaussian',.25);

3. noise_salt&pepper=imnoise(image,'salt&pepper',.25);

would it means that we had addded 25% of different types of noise to an image ??

thanks budddy

what are the difference between salt and pepper noise and gaussian noise? and what are the Matlab codes to add both noises separately to an ECG signal? please help.

How to add RVIN

why u have to add salt and pepper noise to image?

## Enjoyed Reading? Share Your Views