When i looked in to the algorithm of Salt n Pepper noise in a Matlab i've found this,

case 'salt & pepper' % Salt & pepper noise
    b = a;
    x = rand(sizeA);
    d = find(x < p3/2);
    b(d) = 0; % Minimum value
    d = find(x >= p3/2 & x < p3);
    b(d) = 1; % Maximum (saturated) value

Which i simplified as this,

% [a, code, classIn, classChanged, p3, p4]
% p3 = density
% p4 = variance
% a = Image
% code = noise Type 
% classIn = Image Class i.e unit8 , unit16, double

% -------- ALGORITHM ----------%

%     b = a;   <-- Assign b to the input image
%     x = rand(sizeA); <--- Generate random pixels from the image pixels
%     d = find(x < p3/2); <--- Find the pixels whose values are less than half of the mean value  
%     b(d) = 0 <-- Implement minimum noise to them
%     d = find(x >= p3/2 & x < p3) <--- Find the pixels whose values are
%                                        greater than half of the mean
%                                        value & less than mean value
%     b(d) = 1;     <-- Implement maximum noise to them

instead of using imnoise, I am trying to add Salt n Pepper noise manually into the image using the above algorithm,

I = imread('2.jpg');
J = rgb2gray(I);
p3=0.05 %default
b = J;
x = rand(size(b));
d = find(x < p3/2);
b(d) = 0; % Minimum value
d = find(x >= p3/2 & x < p3);
b(d) = 1; % Maximum (saturated) value

I don't know where the final image is stored as when i use imshow for b it show a simple image without salt n pepper noise. Where the final image is stored ? how can i see the it ?

P.S: What does it mean by image class ? that is unit8 , unit16 ?

  • $\begingroup$ b(d) = 255; % Maximum (saturated) value This worked for me . $\endgroup$
    – user4838
    Jun 17, 2013 at 18:17

1 Answer 1


It seems that the final image is in the variable "b". Observe that the max (salt) and min (pepper) values are respectively 1 and 0. This indicates that your original image needs to be an intensity image with graylevels normalized to [0,1]. This may be the reason why you don't see a sensible result when you display "b" as an image.

In case your image is grayscale {0,...,255} i.e. 8-bit unsigned integer format (unit8), you can change your code to assign 0 and 255 instead of 0 and 1.

I suggest you read the documentation on various image storage types here: http://www.mathworks.com/help/toolbox/images/f14-13543.html

It can get pretty confusing at times, mainly because there are so many names (intensity image, grayscale image, RGB, HSV, binary image, indexed image, etc.)


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.