# cc2bw

Convert connected components to binary image

Since R2024a

## Description

BW = cc2bw(CC) creates a binary image from the connected components (objects) in CC.

example

BW = cc2bw(CC,ObjectsToKeep=objectsToKeep) creates a binary image from a subset of connected components, specified by objectsToKeep.

example

## Examples

collapse all

imshow(I)

Create a connected components structure.

CC = bwconncomp(I);

Filter the structure and keep round objects. Display the filtered image.

CC = bwpropfilt(CC,"Circularity",[0.7 1]);
imshow(cc2bw(CC))

Filter the structure again and keep large objects. Display the filtered image.

CC = bwpropfilt(CC,"Area",[20 Inf]);
imshow(cc2bw(CC))

Read a binary image and detect the connected components.

CC = bwconncomp(BW);

Measure the area of each connected component and return the results as a table.

p = regionprops("table",CC,"Area");

Create a binary image that contains only the 2nd through 10th largest connected components. Display the result.

[~,idx] = sort(p.Area,"descend");
BWfilt = cc2bw(CC,ObjectsToKeep=idx(2:10));
imshow(BWfilt)

Read a grayscale image of grains of rice, then convert the image to binary.

BW = imbinarize(I);
imshow(BW)

Measure the area and bounding box of each region.

CC = bwconncomp(BW);
stats = regionprops("table",CC,"Area","BoundingBox");

Select regions for whom these conditions apply:

• The area is greater than 50 pixels

• The bounding box is less than 15 pixels wide and is greater than or equal to 20 pixels tall.

area = stats.Area;
bbox = stats.BoundingBox;
selection = (area > 50) & (bbox(:,3) < 15) & (bbox(:,4) >= 20);
BW2 = cc2bw(CC,ObjectsToKeep=selection);

Display the filtered image.

imshow(BW2)

## Input Arguments

collapse all

Connected components (objects), specified as a structure with four fields.

FieldDescription
ConnectivityConnectivity of the connected components
ImageSizeSize of the binary image
NumObjectsNumber of connected components in the binary image.
PixelIdxList1-by-NumObjects cell array where the k-th element in the cell array is a vector containing the linear indices of the pixels in the k-th object.

Objects to keep, specified as one of these values.

• Positive integer or vector of positive integers — Keep the object or objects whose index is included in objectsToKeep. The length of objectsToKeep is less than or equal to CC.NumObjects.

• Logical vector — Keep the objects whose corresponding element in objectsToKeep is true. The length of objectsToKeep must be equal to CC.NumObjects.

## Output Arguments

collapse all

Binary image, returned as a logical array of the same size as CC.ImageSize.

Data Types: logical

## Version History

Introduced in R2024a

expand all