user2307268
user2307268

Reputation:

Compute contour of a binary image using matlab

I am trying to compute contour of a binary image. Currently i identify the first non zero and the last non zero pixel in the image through looping. Is there a better way? i have encountered few functions:

imcontour(I)
bwtraceboundary(bw,P,fstep,conn,n,dir)

But the first doesn't return the x and y coordinates of the contour. The second function requires a seed point which i cannot provide. An example of the image is shown below. Thanks.

enter image description here

Upvotes: 0

Views: 2100

Answers (3)

NelsonOrange
NelsonOrange

Reputation: 35

I had the same problem, stumbled across this question and just wanted to add that imcontour(Img); does return a matrix. The first row contains the x-values, the second row contains the y-values.

contour = imcontour(Img); x = contour(1,:); y = contour(2,:);

But I would discard the first column.

Upvotes: 1

Imanol Luengo
Imanol Luengo

Reputation: 15889

@rayryeng have already provided the correct answer. As another approach (might be that bwperim performs this operations internally) boundaries of a binary image can be obtained by calculating the difference between the dilated and the eroded image.

For a given image:

im = im2bw(imread('https://i.sstatic.net/yAZ5L.png'));

and a given binary structural element:

selem = ones(3,3); %// square, 8-Negihbours
% selem = [0 1 0; 1 0 1; 0 1 0]; %// cross, 4-Neighbours

The contour of the object can be extracted as:

out = imerode(im, selem) ~= imdilate(im, selem);

enter image description here

Here, however, the boundary is thicker than using bwperim, as the pixels are masked in both inside and outside of the object.

Upvotes: 2

rayryeng
rayryeng

Reputation: 104464

I'm surprised you didn't see bwperim. Did you not try bwperim? This finds the perimeter pixels of all closed objects that are white in a binary image. Using your image directly from StackOverflow:

im = im2bw(imread('https://i.sstatic.net/yAZ5L.png')); 
out = bwperim(im);
imshow(out);

We get:

enter image description here

Upvotes: 6

Related Questions