MATLAB: I’m confused about the function imnoise

image processingimnoiseprobability density

I debuged the function imnoise to add Gaussian noise. I entered following code
f = zeros(255);
noisedImg = imnoise(f, 0, 0.01);
Then I looked at the noisedImg data and found that all pixel values were greater than or equal to zero. I mean that pixel values should be distributed nearly to zero, some are greater than zero and others may be less than zero. I'm puzzled that why there are no pixel values less than zero.

Best Answer

I guess because it expects the output to be the same type as the input, and imnoise expects that if a double is being passed in it has to have a range of 0-1, so it clips anything less than 0 to 0. You would have to use randn() if you wanted negative values in a floating point image. Here is the corrected code:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
originalImage = zeros(255);
noisyImage = imnoise(originalImage, 'Gaussian', 0, 0.01);
% Display the image.

subplot(2, 2, 1);
imshow(noisyImage, []);
title('Noisy Image with imnoise()', 'FontSize', fontSize, 'Interpreter', 'None');
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
% Get rid of tool bar and pulldown menus that are along top of figure.
set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
% Let's compute and display the histogram.

subplot(2, 2, 2);
histogram(noisyImage);
grid on;
title('Histogram of noisy image from imnoise()', 'FontSize', fontSize, 'Interpreter', 'None');
xlabel('Gray Level', 'FontSize', fontSize);
ylabel('Pixel Count', 'FontSize', fontSize);
noisyImage = originalImage + 0.01 * randn(size(originalImage));
% Display the image.
subplot(2, 2, 3);
imshow(noisyImage, []);
title('Noisy Image with randn()', 'FontSize', fontSize, 'Interpreter', 'None');
% Let's compute and display the histogram.
subplot(2, 2, 4);
histogram(noisyImage);
grid on;
title('Histogram of noisy image with randn()', 'FontSize', fontSize, 'Interpreter', 'None');
xlabel('Gray Level', 'FontSize', fontSize);
ylabel('Pixel Count', 'FontSize', fontSize);