]> Creatis software - CreaPhase.git/blob - octave_packages/image-1.0.15/entropy.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / image-1.0.15 / entropy.m
1 ## Copyright (C) 2008 Søren Hauberg
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 3 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, write to the Free Software
15 ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
17 ## -*- texinfo -*-
18 ## @deftypefn {Function File} {@var{E} =} entropy (@var{im})
19 ## @deftypefnx{Function File} {@var{E} =} entropy (@var{im}, @var{nbins})
20 ## Computes the entropy of an image.
21 ##
22 ## The entropy of the elements of the image @var{im} is computed as
23 ##
24 ## @example
25 ## @var{E} = -sum (@var{P} .* log2 (@var{P})
26 ## @end example
27 ##
28 ## where @var{P} is the distribution of the elements of @var{im}. The distribution
29 ## is approximated using a histogram with @var{nbins} cells. If @var{im} is
30 ## @code{logical} then two cells are used by default. For other classes 256 cells
31 ## are used by default.
32 ##
33 ## When the entropy is computed, zero-valued cells of the histogram are ignored.
34 ##
35 ## @seealso{entropyfilt}
36 ## @end deftypefn
37
38 function retval = entropy (I, nbins = 0)
39   ## Check input
40   if (nargin == 0)
41     error ("entropy: not enough input arguments");
42   endif
43   
44   if (!ismatrix (I))
45     error ("entropy: first input must be a matrix");
46   endif
47   
48   if (!isscalar (nbins))
49     error ("entropy: second input argument must be a scalar");
50   endif
51   
52   ## Get number of histogram bins
53   if (nbins <= 0)
54     if (islogical (I))
55       nbins = 2;
56     else
57       nbins = 256;
58     endif
59   endif
60   
61   ## Compute histogram
62   P = hist (I (:), nbins, true);
63   
64   ## Compute entropy (ignoring zero-entries of the histogram)
65   P += (P == 0);
66   retval = -sum (P .* log2 (P));
67 endfunction