MATLAB: Find borders of a truth map

borderimagesc

Hi,
I have an array
truth_map =
[0 0 0 0 0 0 0 0 1 1 ;
0 0 0 0 0 0 0 0 1 1 ;
0 0 0 0 0 0 0 1 1 1 ;
0 0 0 0 0 0 1 1 1 0 ;
0 0 0 0 0 1 1 1 1 0 ;
0 1 1 1 1 0 0 0 0 0 ;
1 1 1 1 1 0 0 0 0 0 ;
1 1 1 1 1 0 0 0 0 0 ;
1 1 1 1 0 0 0 0 0 0 ;
1 1 1 0 0 0 0 0 0 0 ; ]
Which I want to make look like this:
truth_map =
[0 0 0 0 0 0 0 0 1 0 ;
0 0 0 0 0 0 0 0 1 0 ;
0 0 0 0 0 0 0 1 0 1 ;
0 0 0 0 0 0 1 0 1 0 ;
0 0 0 0 0 1 1 1 1 0 ;
0 1 1 1 1 0 0 0 0 0 ;
1 0 0 0 1 0 0 0 0 0 ;
0 0 0 0 1 0 0 0 0 0 ;
0 0 0 1 0 0 0 0 0 0 ;
0 0 1 0 0 0 0 0 0 0 ; ]
This is trivial to do by hand for small arrays but my array is 1000×1000 and the area's are randomly shaped.
What would be a good way to just get an array of the borders?
Thanks, Daniel

Best Answer

  • The way you've defined your edges they correspond to either transition from 0 to 1 or from 1 to 0 when scanning from left to right or top to bottom. This is easily detected by diff:
    m = [0 0 0 0 0 0 0 0 1 1 ;
    0 0 0 0 0 0 0 0 1 1 ;
    0 0 0 0 0 0 0 1 1 1 ;
    0 0 0 0 0 0 1 1 1 0 ;
    0 0 0 0 0 1 1 1 1 0 ;
    0 1 1 1 1 0 0 0 0 0 ;
    1 1 1 1 1 0 0 0 0 0 ;
    1 1 1 1 1 0 0 0 0 0 ;
    1 1 1 1 0 0 0 0 0 0 ;
    1 1 1 0 0 0 0 0 0 0 ; ]
    m2 = [zeros(1, size(m, 2)); diff(m) == 1] | ... 0 to 1 from top to bottom
    [diff(m) == -1; zeros(1, size(m, 2))] | ... 1 to 0 from top to bottom
    [zeros(size(m, 1), 1), diff(m, [], 2) == 1] | ... 0 to 1 from left to right
    [diff(m, [], 2) == -1, zeros(size(m, 1), 1)] % 1 to 0 from left to right