Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

8 Adjacency

Certainly! Let's break down the code step by step:

1. **Read Grayscale Image:**


```matlab
grayImage = imread('your_binary_image.png');
```
Reads the image file specified by 'your_binary_image.png' into the variable
`grayImage`. This assumes the image is grayscale. If the image is already binary,
this step may be unnecessary.

2. **Convert to Binary Image:**


```matlab
binaryImage = im2bw(grayImage);
```
Converts the grayscale image (`grayImage`) into a binary image (`binaryImage`)
using the `im2bw` function. This function threshold the intensity values to create a
black and white image.

3. **Find Connected Components:**


```matlab
connectedComponents = bwlabel(binaryImage, 8);
```
Uses the `bwlabel` function to label connected components in the binary image
(`binaryImage`). The '8' parameter specifies 8-connected components (considering
pixels in all 8 neighboring directions).
4. **Display Original and Labeled Images:**
```matlab
figure;

subplot(1, 2, 1);
imshow(binaryImage);
title('Original Binary Image');

subplot(1, 2, 2);
imshow(label2rgb(connectedComponents, 'jet', 'k', 'shuffle'));
title('Connected Components');
```
Sets up a figure with two subplots. The first subplot displays the original binary
image (`binaryImage`). The second subplot uses `label2rgb` to create a color-coded
image of the connected components and displays it.

5. **Count the Number of Connected Components:**


```matlab
numComponents = max(connectedComponents(:));
fprintf('Number of connected components: %d\n', numComponents);
```
Counts the number of unique connected components by finding the maximum
label value in the labeled image. Then, it prints the result to the MATLAB
command window.
The purpose of this code is to load a binary image, find connected components,
display the original and labeled images, and output the number of connected
components. The color-coded display helps visualize different connected
components in the image.

You might also like