]> Creatis software - CreaPhase.git/blob - octave_packages/image-1.0.15/medfilt2.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / image-1.0.15 / medfilt2.m
1 ## Copyright (C) 2000 Teemu Ikonen
2 ##
3 ## This program is free software; you can redistribute it and/or
4 ## modify it under the terms of the GNU General Public License
5 ## as published by the Free Software Foundation; either version 2
6 ## of the License, or (at your option) any later version.
7 ##
8 ## This program is distributed in the hope that it will be useful, but
9 ## WITHOUT ANY WARRANTY; without even the implied warranty of
10 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 ## 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} {} medfilt2(@var{A}, [@var{domain}, @var{padding}])
18 ## Two dimensional median filtering.
19 ##
20 ## Replaces elements of @var{A} with the median of their neighbours defined 
21 ## by true elements of logical matrix @var{domain}. The default @var{domain} 
22 ## is a 3 by 3 matrix with all elements equal to 1. If @var{domain} is 1 by 2
23 ## row vector, the domain matrix will be 
24 ## logical(ones(@var{domain}(2), @var{domain}(1))).
25 ##
26 ## Optional variable @var{padding} defines the padding used in augmenting 
27 ## the borders of @var{A}. See impad for details.
28 ##
29 ## @seealso{ordfilt2}
30 ## @end deftypefn
31
32 ## Author: Teemu Ikonen <tpikonen@pcu.helsinki.fi>
33 ## Created: 5.5.2000
34 ## Keywords: image processing median filtering
35
36 %!test
37 %! b = [0,1,2,3;1,8,12,12;4,20,24,21;7,22,25,18];
38 %! assert(medfilt2(b),[0,1,2,0;1,4,12,3;4,12,20,12;0,7,20,0]);
39
40 function retval = medfilt2(A, varargin)
41
42 padding = "zeros";
43 domain = logical(ones(3,3));
44
45 for i=1:length(varargin)
46   a = varargin{i};
47   if(ischar(a))
48     padding = a;
49   elseif(isvector(a) && size(a) == [1, 2])
50     domain = logical(ones(a(2), a(1)));
51   elseif(ismatrix(a))
52     domain = logical(a);
53   endif
54 endfor
55
56 n = sum(sum(domain));
57 if((n - 2*floor(n/2)) == 0) % n even - more work
58   nth = floor(n/2);
59   a = ordfilt2(A, nth, domain, padding);
60   b = ordfilt2(A, nth + 1, domain, padding);
61   retval = a./2 + b./2; # split into two divisions to avoid overflow on integer data
62 else
63   nth = floor(n/2) + 1;
64   retval = ordfilt2(A, nth, domain, padding);
65 endif
66
67 endfunction