Connected Component labeling without using bwlabel or bwconncomp functions ?
Show older comments
I have written a code for labelling and counting number of connected components in binary image. But I am not getting expected results. Can anyone find where I am making mistake ? My code is :
function cca()
A=imread('contours.jpg');
figure,imshow(A);
title('Original Image');
% k indicates number of components in binary image
k = 0;
global B;
B = zeros(size(A,1),size(A,2));
% to make sure boundary conditions, skip first row, column and last row,
% column. These will be taken care by recursive function calls later
for i = 2 : size(A,1) - 1
for j = 2 : size(A,2) - 1
if A(i,j) == 1 && B(i,j) == 0
k = k + 1;
rcca(i,j,A,k);
end
end
for i = 1 : size(A,1)
if A(i,1) == 1 && B(i,1) == 0
k = k + 1;
B(i,1) = k;
else
if A(i,size(A,2)) == 1 && B(i,size(A,2)) == 0
k = k + 1;
B(i,size(A,2)) = k;
end
end
end
for j = 1 : size(A,2)
if A(1,j) == 1 && B(1,j) == 0
k = k + 1;
B(1,j) = k;
else
if A(size(A,1),j) == 1 && B(size(A,1),j) == 0
k = k + 1;
B(size(A,1),j) = k;
end
end
end
fprintf('\ntotal number of components in image = %.0f\n',k);
Function rcca is as follows :
function rcca(x,y,A,k)
global B;
B(x,y) = k;
% dx and dy is used to check for 8 - neighbourhood connectivity
dx = [-1,0,1,1,1,0,-1,-1];
dy = [1,1,1,0,-1,-1,-1,0];
if x > 1 && y > 1 && x < size(A,1) && y < size(A,2)
for i = 1 : 8
nx = x + dx(i);
ny = y + dy(i);
if A(nx,ny) == 1 && B(nx,ny) == 0
rcca(nx,ny,A,k);
end
end
end
Please help me in finding logical error. Here is my image :

Accepted Answer
More Answers (1)
Image Analyst
on 24 Sep 2015
0 votes
I really don't know why you don't just use the solution I gave you, and you accepted, in your duplicate question. What was wrong with it? It worked. Why do you prefer to go through all that complicated stuff, instead of a single line of code, especially since you say it's not working?
1 Comment
Sumit Khatri
on 24 Sep 2015
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!