%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Connected Components

c=imread('chess.jpg');
figure; imshow(c)

b=im2bw(c, 0.5);
figure; imshow(b)

bi= ~b;
imshow(bi)

[L, num]=bwlabel(bi);
figure; imshow(L)
figure; imagesc(L)

%% Get Area
AA = regionprops(L,'Area'); 
AA(1).Area
AA(2).Area
AA(3).Area


% For 8 connected components
[L, num]=bwlabel(bi, 8);

% Display it with color
imshow(label2rgb(L))
 
%%%%%%%%%%%%%%%
% Centroids

CC = regionprops(L,'Centroid');
 
figure
hold on
for i=1:num
  %CC(i).Centroid
  plot(CC(i).Centroid(1), CC(i).Centroid(2), 'r.')
end

%figure;
%plot(CC(3).Centroid(1), CC(3).Centroid(2), 'r.')


%% Delete stuff (remove the connected component with label 1)
res=find(L==1);

L(res)=0;
figure; imshow(L)


%% Delete stuff (remove the connected component with label 5)
res=find(L==5);

L(res)=0;
figure; imshow(L)

% create a new image that contains only the knight
[rows, cols]= size(L);
K= zeros(rows, cols);
K(res)=1;
figure; imshow(K)
