简体   繁体   中英

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.

在此处输入图片说明

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('http://i.stack.imgur.com/yAZ5L.png')); 
out = bwperim(im);
imshow(out);

We get:

在此处输入图片说明

@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('http://i.stack.imgur.com/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);

在此处输入图片说明

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM