Matlab Code for Adding salt and pepper noise to 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. 
Learn how to remove the noise without using the 'medfilt2' function.


Contact:
Mr. Roshan P. Helonde
Mobile: +91-7276355704
WhatsApp: +91-7276355704
Email: roshanphelonde@rediffmail.com
Share:

Total Pageviews

CONTACT US

Prof. Roshan P. Helonde
Mobile: +917276355704
WhatsApp: +917276355704
Email: roshanphelonde@rediffmail.com

Enter Project Title

Popular Projects

All Archive

Contact Form

Name

Email *

Message *