]> Creatis software - CreaPhase.git/blob - octave_packages/image-1.0.15/imnoise.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / image-1.0.15 / imnoise.m
1 ## Copyright (C) 2000 Paul Kienzle
2 ##
3 ## This program is free software; you can redistribute it and/or modify
4 ## it under the terms of the GNU General Public License as published by
5 ## the Free Software Foundation; either version 2 of the License, or
6 ## (at your option) any later version.
7 ##
8 ## This program is distributed in the hope that it will be useful,
9 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
10 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 ## GNU General Public License for more details.
12 ##
13 ## You should have received a copy of the GNU General Public License
14 ## along with this program; If not, see <http://www.gnu.org/licenses/>.
15
16 ## -*- texinfo -*-
17 ## @deftypefn {Function File} {@var{B} =} imnoise (@var{A}, @var{type})
18 ## Adds noise to image in @var{A}.
19 ##
20 ## @table @code
21 ## @item imnoise (A, 'gaussian' [, mean [, var]])
22 ## additive gaussian noise: @var{B} = @var{A} + noise
23 ## defaults to mean=0, var=0.01
24 ## @item  imnoise (A, 'salt & pepper' [, density])
25 ## lost pixels: A = 0 or 1 for density*100% of the pixels
26 ## defaults to density=0.05, or 5%
27 ## @item imnoise (A, 'speckle' [, var])
28 ## multiplicative gaussian noise: @var{B} = @var{A} + @var{A}*noise
29 ## defaults to var=0.04
30 ## @end table
31 ## @end deftypefn
32
33 ## Modified: Stefan van der Walt <stefan@sun.ac.za>, 2004-02-24
34
35 function A = imnoise(A, stype, a, b)
36
37   if (nargin < 2 || nargin > 4 || !ismatrix(A) || !ischar(stype))
38     usage("B = imnoise(A, type, parameters, ...)");
39   endif
40   
41   valid = (min(A(:)) >= 0 && max(A(:)) <= 1);
42
43   stype = tolower(stype);
44   if (strcmp(stype, 'gaussian'))
45     if (nargin < 3), a = 0.0; endif
46     if (nargin < 4), b = 0.01; endif
47     A = A + (a + randn(size(A)) * sqrt(b));
48     ## Variance of Gaussian data with mean 0 is E[X^2]
49   elseif (strcmp(stype, 'salt & pepper'))
50     if (nargin < 3), a = 0.05; endif
51     noise = rand(size(A));
52     A(noise <= a/2) = 0;
53     A(noise >= 1-a/2) = 1;
54   elseif (strcmp(stype, 'speckle'))
55     if (nargin < 3), a = 0.04; endif
56     A = A .* (1 + randn(size(A))*sqrt(a));
57   else
58     error("imnoise: use type 'gaussian', 'salt & pepper', or 'speckle'");
59   endif
60   
61   if valid
62     A(A>1) = 1;
63     A(A<0) = 0;
64   else
65     warning("Image should be in [0,1]");
66   endif
67
68 endfunction
69
70 %!assert(var(imnoise(ones(10)/2,'gaussian')(:)),0.01,0.005) # probabilistic
71 %!assert(length(find(imnoise(ones(10)/2,'salt & pepper')~=0.5)),5,10) # probabilistic
72 %!assert(var(imnoise(ones(10)/2,'speckle')(:)),0.01,0.005) # probabilistic