• Status: Solved
• Priority: Medium
• Security: Public
• Views: 2124

# bwtraceboundary

Hello,

Can someone explain me what the following code does ?

``````BW = imread('blobs.png');
imshow(BW,[]);
s=size(BW);
for row = 2:55:s(1)
for col=1:s(2)
if BW(row,col),
break;
end
end

contour = bwtraceboundary(BW, [row, col], 'W');
``````
0
unknown_
• 2
1 Solution

Commented:
This code is extract from Matlab's help of bwtraceboundary function.
http://www.mathworks.com/access/helpdesk/help/toolbox/images/bwtraceboundary.html
You show here only part of the code. The full code is below. What the code does is there as well:

Read in and display a binary image. Starting from the top left, project a beam across the image searching for the first nonzero pixel. Use the location of that pixel as the starting point for the boundary tracing. Including the starting point, extract 50 pixels of the boundary and overlay them on the image. Mark the starting points with a green x. Mark beams that missed their targets with a red x.

Do you need line-by-line description? Which lines you don't understand exactly?
``````BW = imread('blobs.png');
imshow(BW,[]);
s=size(BW);
for row = 2:55:s(1)
for col=1:s(2)
if BW(row,col),
break;
end
end

contour = bwtraceboundary(BW, [row, col], 'W', 8, 50,...
'counterclockwise');
if(~isempty(contour))
hold on;
plot(contour(:,2),contour(:,1),'g','LineWidth',2);
hold on;
plot(col, row,'gx','LineWidth',2);
else
hold on; plot(col, row,'rx','LineWidth',2);
end
end
``````
0

Author Commented:
can someone explain what's the purpose of that for loop in the code ?

for row = 2:55:s(1)
for col=1:s(2)
if BW(row,col),
break;
end
end
0

Commented:
The first FOR loop goes through rows starting at row 2, then 2+55=57 row, 112, etc.
The second FOR loop scans all pixels in the selected row and stops at the first one, which is not 0 (not black).
Then it doing bwtraceboundary starting at selecting point (with coordinates row and col), initial direction West, 8-connected neighborhood connectivity, up to 50 boundary pixels, search in counterclockwise direction.
If it finds something the script then plots initial point and the contour in green, if not - the initial point in red.
That's all.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.