imnoise.m

来自「有关matlab的电子书籍有一定的帮助希望有用」· M 代码 · 共 101 行

M
101
字号
function b = imnoise(a,type,P1,P2)
%IMNOISE Add noise to image.
%   J = IMNOISE(I,TYPE,...) adds noise of type TYPE to the
%   intensity image I.  TYPE is a string that can have one of
%   these values:
%
%       'gaussian'       for Gaussian white noise
%
%       'salt & pepper'  for "on and off" pixels
%
%       'speckle'        for multiplicative noise
%
%   Depending on TYPE, you can specify additional parameters to
%   IMNOISE.
%   
%   J = IMNOISE(I,'gaussian',M,V) adds Gaussian white noise of
%   mean M and variance V to the image I. The default is zero
%   mean noise with 0.01 variance. 
%   
%   J = IMNOISE(I,'salt & pepper',D) adds salt and pepper noise
%   to the image I, where D is the noise density.  This affects
%   approximately D*PROD(SIZE(I)) pixels. The default is 0.05
%   noise density.
%   
%   J = IMNOISE(I,'speckle',V) adds multiplicative noise to the
%   image I, using the equation J = I + n*I, where n is uniformly
%   distributed random noise with mean 0 and variance V.  The
%   default for V is 0.04. 
%
%   Class Support
%   -------------
%   The input image I can be of class uint8 or double. The output
%   image J is of the same class as I.
%
%   Example
%   -------
%        I = imread('eight.tif');
%        J = imnoise(I,'salt & pepper', 0.02);
%        imshow(I), figure, imshow(J)
%
%   See also RAND, RANDN.

%   Clay M. Thompson 2-24-93
%   Copyright 1993-1998 The MathWorks, Inc.  All Rights Reserved.
%   $Revision: 5.8 $  $Date: 1997/11/24 15:35:28 $

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

if ~isstr(type), error('TYPE must be a string.'); end
type = [type '  '];
code = lower(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
    if isa(a, 'uint8'),        
        a = double(a)/255; 
        uint8input = 1;
    else 
        uint8input = 0;
    end
    b = a + sqrt(P2)*randn(size(a)) + P1;
    b = max(0,min(b,1)); % Truncate if necessary
    if uint8input==1,
        b = uint8(round(b*255));
    end
        
elseif all(code=='sa'), % Salt & pepper noise
    if nargin<3, P1 = 0.05; end % Noise density
    b = a;
    x = rand(size(a));
    d = find(x < P1/2);
    b(d) = 0;
    d = find(x >= P1/2 & x < P1);
    if isa(a, 'uint8')
        b(d) = 255;
    else
        b(d) = 1;
    end

elseif all(code=='sp'), % Speckle (multiplicative) noise
    if nargin<3, P1 = .04; end
    if isa(a, 'uint8'),        
        a = double(a)/255; 
        uint8input = 1;
    else 
        uint8input = 0;
    end
    b = a + sqrt(12*P1)*a.*(rand(size(a))-.5);
    b = max(0,min(b,1)); % Truncate if necessary
    if uint8input==1,
        b = uint8(round(b*255));
    end

else
    error('Unknown noise type.')
    
end

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?