# Adjacency, Connectivity and Component Labelling

Adjacency and connectivity are used to define the basic relationship between the pixel values. There are various ways in which the pixel values can be adjacent to each other or connected, viz. 4-adjacency, 8-adjacency and m-adjacency; and correspondingly 4-connectivity, 8-connectivity and m-connectivity.

In order to identify objects in a digital pattern, we need to locate groups of black pixels that are “connected” to each other. In other words, the objects in a given digital pattern are the connected components of that pattern. And pixels can be connected when they exhibit one of the various types of adjacency.

**Program to demonstrate Connectivity**

Create a checker board pattern and count the number of objects using 4 and 8 connectivity.

`clc; clear all;close all`

```
```I=checkerboard(20);

figure,imshow(I);

[l num]=bwlabel(I); % check the number of objects using 4 and 8

RGB=label2rgb(l); %Display the objects using conversion label2rgb

figure,imshow(RGB)

Program to demonstrate that Connectivity helps in

1) applying bounding box for selected Objects

2) calculate

i)area ii) mean iii)centroid iv) perimeter

clc; clear all; close all;

I=imread('coins.png');

figure,imshow(I);

B=im2bw(I);

figure,imshow(B);

c=imfill(B,'holes'); % Fill the holes

figure,imshow(c);

[label,num]=bwlabel(c); %label the image

display(num)

object=3; % To apply bounding box for labelled 3

[row col]=find(label==object); % to find the coordinates of the bounding box

sx=min(col)-0.5;

sy=min(row)-0.5;

breadth=max(col)-min(col)+1;

len=max(row)-min(row)+1;

bbox=[sx sy breadth len];

display(bbox);

figure,imshow(I);

hold on;

```
```x=zeros([1 5]);

y=zeros([1 5]);

x(:)=bbox(1);

y(:)=bbox(2);

x(2:3)=bbox(1)+bbox(3);

y(3:4)=bbox(2)+bbox(4);

plot(x,y);

obj_area=numel(row);

display(obj_area);

% Finding Centroid

X=mean(col);

Y=mean(row);

Centroid=[X Y];

display(Centroid);

plot(X, Y,'o','color','r');

hold off

% Perimeter calculation

BW=bwboundaries(label==object);

figure, imshow(I);

hold on

visboundaries(BW);

c=cell2mat(BW(1));

perimeter=0;

for i=1:size(c,1)-1

perimeter=perimeter+sqrt((c(i,1)-c(i+1,1)^2+c(i+1,2)).^2);

end

display(perimeter);

%calculation with region propeerties for verification purpose

sdata=regionprops(label,'all'); % click on sdata and check for different parameters

Thus, adjacency, connectivity and component labelling can be summed up here.

Check out the next article on Arithmetic operations on Digital Images of Digital Image.

Go back to Spatial resolution and quantization of digital image