Wolpertinger
Wolpertinger

Reputation: 1301

Determine matrix boundary without loops

I have got a 2D matrix. There is some region in the matrix where the elements are non-zero, in particular everywhere around the edge they are zero.

I plot the matrix using image as a colorplot and would like to add the curve that shows the boundary between non-zero values to zero values in the matrix. Is there any neat way to do this without loops?

Upvotes: 4

Views: 150

Answers (2)

Ander Biguri
Ander Biguri

Reputation: 35525

Another option is using the image processing toolbox and the bwperim function. This will work if you know that your area is completely closed (i.e. has no holes in the boundary)

This is an example using a black and white image, and you have 2 options: fill the inner gaps before, or not. You can see in the result the differences.

A = imread('circles.png');

Afill=imfill(A,'holes'); % optional
Abound1=bwperim(Afill);
Abound2=bwperim(A);
imshow([A,Abound, Abound2])

enter image description here

You can plot one on top of the other with:

[x,y]= find(Abound2);
hold on
image(A*255)  %// If A is logical, else use just A (not *255)
colormap('gray')
plot(y,x,'r.')
hold off
axis tight

enter image description here

If you have a gray-scale image (or a matrix with a single value in each position (2D matrix), then you can binarize it first by either:

  1. If you know everything outside your object is EXACTLY zero A=yourA>0;
  2. If you want to separate your object from the background, and the background is not exactly zero by A=im2bw(yourA,level), by choosing your own level, or letting Otsu do it for you with level=graythresh(yourA)

Upvotes: 2

BillBokeey
BillBokeey

Reputation: 3511

This looks like a job for convhull :

To illustrate this code i'll take a dummy example :

A=zeros(10);
B=binornd(1,0.5,8,8);
A(2:end-1,2:end-1)=B

A =

 0     0     0     0     0     0     0     0     0     0
 0     0     0     1     0     0     0     0     0     0
 0     0     1     1     1     1     1     1     0     0
 0     0     1     1     0     0     0     0     1     0
 0     0     0     1     0     0     0     1     0     0
 0     1     0     0     0     0     0     1     0     0
 0     0     0     1     1     1     1     1     1     0
 0     0     1     0     1     1     1     1     0     0
 0     1     0     1     1     1     1     0     1     0
 0     0     0     0     0     0     0     0     0     0

1/ Find the locations of all non zero entries :

[row,col]=find(A);

2/ Take the convex hull of these locations

k=convhull(row,col);

3/ Plot the convex hull (I plot the non zero points aswell but in your problem it will be your image points)

plot(row(k),col(k),'r-',row,col,'b*')

Result :

enter image description here

Upvotes: 6

Related Questions