Shapes and Boundaries 353
To obtain the chain code in MATLAB, we have to write a small f unction to do the job for
us. We have to first be able to trace out the boundary of our object, and once we can do
that, we can write down our directions to form the chain code. A simple boundary following
algorithm has been given by Sonka et al. [49]. For simplicity, we shall j ust give the version
for 4-connected boundaries:
1. Start by finding the pixel in the object that has the left-most value in the topmost
row; call this pixel P
0
. Define a variable dir (for direction), and set it equal to 3.
(Since P
0
is the top left pixel in the object, the direction to the next pixel must be 3.)
2. Traverse the 3 × 3 neighborhood of the current pixel in an anticlockwise direction,
beginning the search at the pixel in direction
dir + 3 (mod 4)
This simp ly sets the current direction to the first direction anticlockwise from
dir:
dir 0 1 2 3
dir + 3 (mod 4) 3 0 1 2
The first foreground pixel will be the new boundary element. Update dir.
3. Stop when the current boundary element P
n
is equal to the second element P
1
and
the previous boundary pixel P
n−1
is equal to the first boundary element P
0
.
Suppose we have a binary image im consisting of a single object. We can find the top left
pixel with the following MATLAB commands:
MATLAB/Octave
>> [x,y] = find(im==1);
>> x = min(x)
>> imx = im(x,:);
>> imy = min(imx)
or in Python with
Python
In : x,y = np.where(im==1)
In : mx = mx.min()
In : my = y[np.where(x==mx)].min()
pixels. The second command finds the minimum of the first coordinates. Thus, mx is the
top row of the object. The third command isolates this top row, and the final command
finds the left-most column in it.
Given the indices
x and y of the current pixel, and the value dir, how do we implement
Step 2? We give a simple example, shown in Figure 12.4. Suppose that in this particular
example, the current value of
dir is 0 so that
dir + 3 (mod 4) = 3.
The dotted arrows indicate the direction of traversing (starting from the pixel in direction
3 from P
k
) until we reach a new foreground pixel. This pixel is then P
k+1
.