1 ## Copyright (C) 2006 Søren Hauberg
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)
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.
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/>.
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.
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.
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.
28 function out = bwperim(bw, n=4)
33 if (!isbw(bw) || ndims(bw)!=2)
34 error("bwperim: first input argument must be a 2-dimensional binary image");
36 if (!isscalar(n) || (n!=4 && n!=8))
37 error("bwperim: second argument must be 4 or 8");
40 ## Make sure bw is logical;
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)];
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);
60 idx = (north == bw) & (south == bw) & (west == bw) & (east == 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);