www.gusucode.com > images 案例代码 matlab源码程序 > images/TraceBoundariesOfObjectsInImagesExample.m

    %% Trace Boundaries of Objects in Images
% This example shows how to trace the border of an object in a binary image
% using |bwtraceboundary| . Then, using |bwboundaries| , the example traces
% the borders of all the objects in the image.
%%
% Read image and display it.

% Copyright 2015 The MathWorks, Inc.

I = imread('coins.png');
imshow(I)
%%
% Convert the image to a binary image. |bwtraceboundary| and |bwboundaries|
% only work with binary images.
BW = im2bw(I);
imshow(BW)
%%
% Determine the row and column coordinates of a pixel on the border of the
% object you want to trace. |bwboundary| uses this point as the starting
% location for the boundary tracing.
dim = size(BW)
col = round(dim(2)/2)-90;
row = min(find(BW(:,col)))
%%
% Call |bwtraceboundary| to trace the boundary from
% the specified point. As required arguments, you must specify a binary
% image, the row and column coordinates of the starting point, and the
% direction of the first step. The example specifies north ( |'N'| ).
boundary = bwtraceboundary(BW,[row, col],'N');
%%
% Display the original grayscale image and use the coordinates returned by
% |bwtraceboundary| to plot the border on the image.
imshow(I)
hold on;
plot(boundary(:,2),boundary(:,1),'g','LineWidth',3);
%%
% To trace the boundaries of all the coins in the image, use the
% |bwboundaries| function. By default, |bwboundaries| finds the boundaries
% of all objects in an image, including objects inside other objects. In
% the binary image used in this example, some of the coins contain black
% areas that |bwboundaries| interprets as separate objects. To ensure that
% |bwboundaries| only traces the coins, use |imfill| to fill the area
% inside each coin. |bwboundaries| returns a cell array, where each cell
% contains the row/column coordinates for an object in the image.
BW_filled = imfill(BW,'holes');
boundaries = bwboundaries(BW_filled);
%%
% Plot the borders of all the coins on the original grayscale image using
% the coordinates returned by |bwboundaries| .
for k=1:10
   b = boundaries{k};
   plot(b(:,2),b(:,1),'g','LineWidth',3);
end