function b = imnoise(a,type,P1,P2)
%IMNOISE Image noise.
%	J = IMNOISE(I,'type',...) adds noise of 'type' to the 
%	intensity image I.  Possibilities are: 'gaussian',
%	'salt & pepper', and 'speckle'.
%
%	J = IMNOISE(I,'gaussian',M,V) adds Gaussian white
%	noise of mean M and variance V to the image I.
%	Default is zero mean noise with 0.01 variance.
%
%	J = IMNOISE(I,'salt & pepper',D) adds salt and
%	pepper noise to the image I.  D is the noise density.
%	Approximately D*PROD(SIZE(I)) pixels will be affected. 
%	Default is 0.05 noise density.
%
%	J = IMNOISE(I,'speckle',V) adds multiplicative noise
%	of variance V to the image I.  Default is 0.04 noise
%	variance.
%
%	See also RAND, RANDN.

%	Clay M. Thompson 2-24-93
%	Copyright (c) 1993 by The MathWorks, Inc.
%	$Revision: 1.6 $  $Date: 1993/08/10 02:20:04 $

error(nargchk(1,4,nargin));
if nargin<2, type = 'gaussian'; end

if ~isstr(type), error('TYPE must be a string.'); end
type = [type '  '];
code = type(1:2);

if all(code=='ga'), % Gaussian white noise
  if nargin<3, P1 = 0; end % Mean
  if nargin<4, P2 = 0.01; end % Variance
  b = a + sqrt(P2)*randn(size(a)) + P1;
  b = max(0,min(b,1)); % Truncate if necessary

elseif all(code=='sa'), % Salt & pepper noise
  if nargin<3, P1 = 0.05; end % Noise density
  b = a;
  d = find(rand(size(a))<P1/2);
  b(d) = zeros(size(d));
  d = find(rand(size(a))<P1/2);
  b(d) = ones(size(d));

elseif all(code=='sp'), % Speckle (multiplicative) noise
  if nargin<3, P1 = .1; end
  b = a + 2*sqrt(P1)*a.*(rand(size(a))-.5);
  b = max(0,min(b,1)); % Truncate if necessary

else
  error('Unknown noise type.')

end
