MATLAB: Making matrix like in Wavefront algorithm
Asked Answered
P

1

6

I have this kind of matrix (13 x 13):

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

Can I somehow increase the values around the central zero and the zeros that make the "walls" by one at each iteration and make it as this?

0   0   0   0   0   0   0   0   0   0   0   0   0
0   1   1   1   1   1   1   1   1   1   1   1   0
0   1   2   2   2   2   2   2   2   2   2   1   0
0   1   2   3   3   3   3   3   3   3   2   1   0
0   1   2   3   2   2   2   2   2   3   2   1   0
0   1   2   3   2   1   1   1   2   3   2   1   0
0   1   2   3   2   1   0   1   2   3   2   1   0
0   1   2   3   2   1   1   1   2   3   2   1   0
0   1   2   3   2   2   2   2   2   3   2   1   0
0   1   2   3   3   3   3   3   3   3   2   1   0
0   1   2   2   2   2   2   2   2   2   2   1   0
0   1   1   1   1   1   1   1   1   1   1   1   0
0   0   0   0   0   0   0   0   0   0   0   0   0
Parallelize answered 11/3, 2015 at 13:59 Comment(0)
B
6

If you have the image processing toolbox, it's a one-liner:

%# assume your matrix is called A
result = bwdist(~A,'cityblock')

'result' is the distance of each non-zero pixel in A to the nearest zero if you can only step horizontally or vertically.

Butylene answered 11/3, 2015 at 14:13 Comment(3)
Thank you very much Jonas. Sorry for disturbing again, but do you know how can I write this function (bwdist) by myself? Do you know related algorithm?Parallelize
@Fabi: If you do not have access to the image processing toolbox, I suggest getting mexopencv and to use their distance transform. It's a lot faster than writing a distance transform yourself. If you really, really do want to cook your own distance transform, have a look at this question for algorithms to implement.Butylene
The algorithm is pretty simple. Initialize the output with 0 wherever you want the final value to be 0, and inf otherwise. Then for each row, do a left-to-right pass wherein you set each value to min(current value, previous value+1). Repeat for each row but going right-to-left, then also do the same for each column first going top-to-bottom, followed by bottom-to-top. In your particular example, you could have of course skipped the initialization step since the 0s are where you want them and everything else is >=1.Selfeffacing

© 2022 - 2024 — McMap. All rights reserved.