]> Creatis software - CreaPhase.git/blob - octave_packages/image-1.0.15/bwperim.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / image-1.0.15 / bwperim.m
1 ## Copyright (C) 2006  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 2, or (at your option)
6 ## 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 file.  If not, see <http://www.gnu.org/licenses/>.
15
16 ## -*- texinfo -*-
17 ## @deftypefn {Function File} @var{BW2} = bwperim(@var{BW1})
18 ## @deftypefnx{Function File} @var{BW2} = bwperim(@var{BW1}, @var{n})
19 ## Find the perimeter of objects in binary images.
20 ##
21 ## A pixel is part of an object perimeter if its value is one and there
22 ## is at least one zero-valued pixel in its neighborhood.
23 ##
24 ## By default the neighborhood of a pixel is 4 nearest pixels, but
25 ## if @var{n} is set to 8 the 8 nearest pixels will be considered.
26 ## @end deftypefn
27
28 function out = bwperim(bw, n=4)
29   ## Input checking
30   if (nargin < 1)
31     print_usage();
32   endif
33   if (!isbw(bw) || ndims(bw)!=2)
34     error("bwperim: first input argument must be a 2-dimensional binary image");
35   endif
36   if (!isscalar(n) || (n!=4 && n!=8))
37     error("bwperim: second argument must be 4 or 8");
38   endif
39   
40   ## Make sure bw is logical;
41   bw = logical (bw);
42   
43   ## Translate image by one pixel in all directions
44   [rows, cols] = size(bw);
45   north = [bw(2:end, :); zeros(1, cols, "logical")];
46   south = [zeros(1, cols, "logical"); bw(1:end-1, :)];
47   west  = [bw(:, 2:end), zeros(rows, 1, "logical")];
48   east  = [zeros(rows, 1, "logical"), bw(:, 1:end-1)];
49   if (n == 8)
50     north_east = north_west = south_east = south_west = zeros (rows, cols, "logical");
51     north_east (1:end-1, 2:end)   = bw (2:end, 1:end-1);
52     north_west (1:end-1, 1:end-1) = bw (2:end, 2:end);
53     south_east (2:end, 2:end)     = bw (1:end-1, 1:end-1);
54     south_west (2:end, 1:end-1)   = bw (1:end-1, 2:end);
55   endif
56   
57   ## Do the comparing
58   if (n == 4)
59     out = bw;
60     idx = (north == bw) & (south == bw) & (west == bw) & (east == bw);
61     out(idx) = false;
62   else # n == 8
63     out = bw;
64     idx = (north == bw) & (north_east == bw) & ...
65           (east  == bw) & (south_east == bw) & ...
66           (south == bw) & (south_west == bw) & ...
67           (west  == bw) & (north_west == bw);
68     out (idx) = false;
69   endif
70 endfunction