Leander Moesinger
Leander Moesinger

Reputation: 2462

Matlab: Finding distance to nearest TRUE value in a matrix

Lets assume I have a logical matrix A (about 1000x1000 size) and want to find for each element the euclidean distance to the nearest TRUE value. How can that be done fast in Matlab?

E.g if i have matrix A:

A = [1 0 0 0
     0 1 1 1
     0 0 0 0
     0 0 1 0]

Then what i want is:

B = [0 1 1 1
     1 0 0 0
     1.41 1 1 1
     2 1 0 1]

One possibility would be imdilate(), but then i would have to dilate a MxN Matrix with a 2Mx2N Matrix, which would take way too long.

I tried calculating the distances from each element to each element==1 using pdist2() and then taking the minimum but that turned out to use way too much memory.

Any suggestions? I would also settle for a solution that just approximates it.

Upvotes: 2

Views: 141

Answers (1)

Suever
Suever

Reputation: 65430

The bwdist function in the Image Processing Toolbox does precisely this

A = [1 0 0 0 
     0 1 1 1
     0 0 0 0
     0 0 1 0];

B = bwdist(A);

%   0.00000   1.00000   1.00000   1.00000
%   1.00000   0.00000   0.00000   0.00000
%   1.41421   1.00000   1.00000   1.00000
%   2.00000   1.00000   0.00000   1.00000

Upvotes: 4

Related Questions