salt and pepper noise in matlab

One simple way to add salt and pepper noise to an image in Matlab is by using the imnoise function. Here is an example:

main.m
original = imread('lena.png'); % or any other image
noisy = imnoise(original, 'salt & pepper', 0.05); % add 5% noise
imshow(noisy);
132 chars
4 lines

The 'salt & pepper' keyword specifies the type of noise to be added, and 0.05 specifies the noise density, i.e., the fraction of pixels that will be affected by the noise. You can adjust 0.05 to add more or less noise.

Another way to add salt and pepper noise is to use a custom function, like this:

main.m
function noisy = saltpepper(original, density)
% original: the original image
% density: the noise density, between 0 and 1
noisy = original;
[r,c] = size(original);
mask = rand(r,c);
noisy(mask < density/2) = 0;
noisy(mask > 1 - density/2) = 255;
end
252 chars
10 lines

This function creates a binary mask of the same size as the original image, with random values between 0 and 1. Pixels with values below density/2 are set to black, and pixels with values above 1 - density/2 are set to white. This creates random black and white dots in the image, simulating salt and pepper noise. You can call this function with an image and a noise density between 0 and 1 to add noise:

main.m
original = imread('lena.png'); % or any other image
noisy = saltpepper(original, 0.05); % add 5% noise
imshow(noisy);
118 chars
4 lines

related categories

gistlibby LogSnag