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.