finding endpoints of a label
2 views (last 30 days)
Show older comments
Hi, I have the following matrix. I =
0 0 0 0
0 1 1 1
0 0 0 0
0 0 0 0
0 0 1 0
0 0 1 0
0 0 1 0
[B,L,N,A]=bwboundaries(I,'noholes');
L =
0 0 0 0
0 1 1 1
0 0 0 0
0 0 0 0
0 0 2 0
0 0 2 0
0 0 2 0
idx=find(L==1) endpoints of label 1 are (2,2) and (2,4)
I need to find that endpoints similarly in case of label 2. Thanks endpoints of label 1 are (2,2) and (2,4)
0 Comments
Accepted Answer
Oleg Komarov
on 26 Jun 2011
Based on the idea of http://www.mathworks.com/matlabcentral/answers/10293-finding-neighbor-of-a-position
I = [0 0 0 0
0 1 1 1
0 0 0 0
1 0 0 0
1 0 0 1
1 0 0 1
1 1 1 1];
[L,num] = bwlabel(I,4);
sz = size(I);
InEn = zeros(num,2);
for n = 1:num
% Find initial point of connected component
InEn(n,1) = find(L == n,1,'first');
l = InEn(n,1);
co = 1;
while true
% row and col subs
[r c] = ind2sub(sz,l(co)); % c = ceil(l/4); r = mod(l,4)+ c*sz(1)
% Calculate 4-connected subs
neigh(1:4,1:2) = [r+[0;-1;+1;0] c+[-1;0;0;1]];
% Convert to positions
idx = (neigh(:,2)-1)*sz(1) + neigh(:,1);
% Keep positions in the range of L
idx = idx(ismember(idx,1:prod(sz)),:);
% Move onto next 4-connected component
co = co+1;
idx = idx(~ismember(idx, l) & L(idx) == n);
% If empty then we reached the end
if idx
l(co) = idx;
else
break
end
end
% Assign end
InEn(n,2) = l(end);
end
2 Comments
More Answers (2)
Walter Roberson
on 26 Jun 2011
B = bwboundaries(I,'noholes');
xy_1_first = B{1}(1,:);
xy_1_last = B{1}(end,:);
xy_2_first = B{2}(1,:);
xy_2_last = B{2}(end,:);
Andrei Bobrov
on 27 Jun 2011
L = bwlabel(I)
I2 = bwmorph(I,'endpoints')
epout = arrayfun(@(i1)find(I2 & L == i1)',1:max(L(:)),'un',0)
example:
I =
0 1 0 1 1 1
1 1 0 0 0 1
1 0 0 0 0 0
1 0 1 1 1 0
0 0 1 0 0 0
0 0 1 0 1 1
0 0 1 0 0 0
0 0 0 0 0 0
1 1 0 0 1 0
0 1 1 0 1 0
0 0 1 0 1 0
0 0 1 0 1 0
0 1 1 0 1 0
0 1 0 0 0 0
0 1 0 1 0 0
0 1 1 1 0 0
0 0 0 0 0 0
>> L = bwlabel(I)
I2 = bwmorph(I,'endpoints');
epout = arrayfun(@(i1)find(I2 & L == i1)',1:max(L(:)),'un',0);
L =
0 1 0 4 4 4
1 1 0 0 0 4
1 0 0 0 0 0
1 0 3 3 3 0
0 0 3 0 0 0
0 0 3 0 5 5
0 0 3 0 0 0
0 0 0 0 0 0
2 2 0 0 6 0
0 2 2 0 6 0
0 0 2 0 6 0
0 0 2 0 6 0
0 2 2 0 6 0
0 2 0 0 0 0
0 2 0 2 0 0
0 2 2 2 0 0
0 0 0 0 0 0
>> epout{5}
ans =
74 91
>>
3 Comments
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!