The OpenCV 3.0 docs for connectedComponents() don't mention Python but it actually is implemented. See for e.g. this SO question. On OpenCV 3.4.0 and above, the docs do include the Python signatures, as can be seen on the current master docs.

The function call is simple: num_labels, labels_im = cv2.connectedComponents(img) and you can specify a parameter connectivity to check for 4- or 8-way (default) connectivity. The difference is that 4-way connectivity just checks the top, bottom, left, and right pixels and sees if they connect; 8-way checks if any of the eight neighboring pixels connect. If you have diagonal connections (like you do here) you should specify connectivity=8. Note that it just numbers each component and gives them increasing integer labels starting at 0. So all the zeros are connected, all the ones are connected, etc. If you want to visualize them, you can map those numbers to specific colors. I like to map them to different hues, combine them into an HSV image, and then convert to BGR to display. Here's an example with your image:

import cv2
import numpy as np

img = cv2.imread('eGaIy.jpg', 0)
img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1]  # ensure binary
num_labels, labels_im = cv2.connectedComponents(img)

def imshow_components(labels):
    # Map component labels to hue val
    label_hue = np.uint8(179*labels/np.max(labels))
    blank_ch = 255*np.ones_like(label_hue)
    labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])

    # cvt to BGR for display
    labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)

    # set bg label to black
    labeled_img[label_hue==0] = 0

    cv2.imshow('labeled.png', labeled_img)
    cv2.waitKey()

imshow_components(labels_im)

Answer from alkasm on Stack Overflow
🌐
PyImageSearch
pyimagesearch.com › home › blog › opencv connected component labeling and analysis
OpenCV Connected Component Labeling and Analysis - PyImageSearch
April 17, 2021 - In this tutorial, you will learn how to perform connected component labeling and analysis with OpenCV. Specifically, we will focus on OpenCV’s most used connected component labeling function, cv2.connectedComponentsWithStats. Connected component labeling (also known as connected component analysis, blob extraction,…
🌐
GeeksforGeeks
geeksforgeeks.org › machine learning › python-opencv-connected-component-labeling-and-analysis
Python OpenCV - Connected Component Labeling and Analysis - GeeksforGeeks
July 23, 2025 - import cv2 import numpy as np # Loading the image img = cv2.imread('Images/img5.png') # preprocess the image gray_img = cv2.cvtColor(img , cv2.COLOR_BGR2GRAY) # Applying 7x7 Gaussian Blur blurred = cv2.GaussianBlur(gray_img, (7, 7), 0) # Applying threshold threshold = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1] # Apply the Component analysis function analysis = cv2.connectedComponentsWithStats(threshold, 4, cv2.CV_32S) (totalLabels, label_ids, values, centroid) = analysis # Initialize a new image to store # all the output components output = np.zeros(gray_img.sha
Top answer
1 of 2
80

The OpenCV 3.0 docs for connectedComponents() don't mention Python but it actually is implemented. See for e.g. this SO question. On OpenCV 3.4.0 and above, the docs do include the Python signatures, as can be seen on the current master docs.

The function call is simple: num_labels, labels_im = cv2.connectedComponents(img) and you can specify a parameter connectivity to check for 4- or 8-way (default) connectivity. The difference is that 4-way connectivity just checks the top, bottom, left, and right pixels and sees if they connect; 8-way checks if any of the eight neighboring pixels connect. If you have diagonal connections (like you do here) you should specify connectivity=8. Note that it just numbers each component and gives them increasing integer labels starting at 0. So all the zeros are connected, all the ones are connected, etc. If you want to visualize them, you can map those numbers to specific colors. I like to map them to different hues, combine them into an HSV image, and then convert to BGR to display. Here's an example with your image:

import cv2
import numpy as np

img = cv2.imread('eGaIy.jpg', 0)
img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1]  # ensure binary
num_labels, labels_im = cv2.connectedComponents(img)

def imshow_components(labels):
    # Map component labels to hue val
    label_hue = np.uint8(179*labels/np.max(labels))
    blank_ch = 255*np.ones_like(label_hue)
    labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])

    # cvt to BGR for display
    labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)

    # set bg label to black
    labeled_img[label_hue==0] = 0

    cv2.imshow('labeled.png', labeled_img)
    cv2.waitKey()

imshow_components(labels_im)

2 of 2
0

My adaptation of the CCL in 2D is:

1) Convert the image into a 1/0 image, with 1 being the object pixels and 0 being the background pixels.

2) Make a 2 pass CCL algorithm by implementing the Union-Find algorithm with pass compression. You can see more here.

In the First pass in this CCL implementation, you check the neighbor pixels, in the case your target pixel is an object pixel, and compare their label between them so that you can generate equivalences between them. You assign the least label, of those neighbor pixels which are objects pixels (label>0) to your target pixel. In this way, you are not only assigning an object label to your target pixesl (label>0) but also creating a list of equivalences.

2) In the second pass, you go through all the pixels, and change their previous label by the label of its parent label by just looking into the equivalent table stored in your Union-Find class.

3)I implemented an additional pass to make the labels follow a sequential order (1,2,3,4....) instead of a random order (23,45,1,...). That involves changing the labels "name" just for aesthetic purposes.

🌐
OpenCV
docs.opencv.org › 3.4 › d3 › dc0 › group__imgproc__shape.html
OpenCV: Structural Analysis and Shape Descriptors
image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 represents the background label. ltype specifies the output label image type, an important consideration based on the total number of labels or alternatively the total number of pixels in the source image. ccltype specifies the connected components labeling algorithm to use, currently Bolelli (Spaghetti) [25], Grana (BBDT) [92] and Wu's (SAUF) [240] algorithms are supported, see the ConnectedComponentsAlgorithmsTypes for details.
🌐
Shimat
shimat.github.io › opencvsharp_docs › html › 1baab192-4d4f-0359-33a3-32ec20b8a721.htm
Cv2.ConnectedComponentsWithStats Method (InputArray, OutputArray, OutputArray, OutputArray, PixelConnectivity, MatType)
Statistics are accessed via stats(label, COLUMN) where COLUMN is one of cv::ConnectedComponentsTypes ... Type: OpenCvSharpOutputArray floating point centroid (x,y) output for each label, including the background label ... Type: OpenCvSharpMatType output image label type. Currently CV_32S and CV_16U are supported. ... [Missing <returns> documentation for "M:OpenCvSharp.Cv2.ConnectedComponentsWithStats(OpenCvSharp.InputArray,OpenCvSharp.OutputArray,OpenCvSharp.OutputArray,OpenCvSharp.OutputArray,OpenCvSharp.PixelConnectivity,OpenCvSharp.MatType)"]
🌐
Shimat
shimat.github.io › opencvsharp_docs › html › 0bb7e2ba-55c3-95f9-210b-125d71b98f5c.htm
Cv2.ConnectedComponents Method (InputArray, Int32[,], PixelConnectivity)
computes the connected components labeled image of boolean image. image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 represents the background label.
Top answer
1 of 4
150

The function works as follows:

# Import the cv2 library
import cv2
# Read the image you want connected components of
src = cv2.imread('/directorypath/image.bmp')
# Threshold it so it becomes binary
ret, thresh = cv2.threshold(src,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# You need to choose 4 or 8 for connectivity type
connectivity = 4  
# Perform the operation
output = cv2.connectedComponentsWithStats(thresh, connectivity, cv2.CV_32S)
# Get the results
# The first cell is the number of labels
num_labels = output[0]
# The second cell is the label matrix
labels = output[1]
# The third cell is the stat matrix
stats = output[2]
# The fourth cell is the centroid matrix
centroids = output[3]

Labels is a matrix the size of the input image where each element has a value equal to its label.

Stats is a matrix of the stats that the function calculates. It has a length equal to the number of labels and a width equal to the number of stats. It can be used with the OpenCV documentation for it:

Statistics output for each label, including the background label, see below for available statistics. Statistics are accessed via stats[label, COLUMN] where available columns are defined below.

  • cv2.CC_STAT_LEFT The leftmost (x) coordinate which is the inclusive start of the bounding box in the horizontal direction.
  • cv2.CC_STAT_TOP The topmost (y) coordinate which is the inclusive start of the bounding box in the vertical direction.
  • cv2.CC_STAT_WIDTH The horizontal size of the bounding box
  • cv2.CC_STAT_HEIGHT The vertical size of the bounding box
  • cv2.CC_STAT_AREA The total area (in pixels) of the connected component

Centroids is a matrix with the x and y locations of each centroid. The row in this matrix corresponds to the label number.

2 of 4
22

I have come here a few times to remember how it works and each time I have to reduce the above code to :

_, thresh = cv2.threshold(src,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
connectivity = 4  # You need to choose 4 or 8 for connectivity type
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh , connectivity , cv2.CV_32S)

Hopefully, it's useful for everyone :)

🌐
OpenCV
docs.opencv.org › 4.x › d0 › d05 › group__cudaimgproc.html
OpenCV: Image Processing
The output is an image where each Connected Component is assigned a unique label (integer value). ltype specifies the output label image type, an important consideration based on the total number of labels or alternatively the total number of pixels in the source image. ccltype specifies the connected components labeling algorithm to use, currently BKE [13] is supported, see the ConnectedComponentsAlgorithmsTypes for details.
Find elsewhere
🌐
GitHub
github.com › ronheywood › opencv › blob › main › basic-connected-components.py
opencv/basic-connected-components.py at main · ronheywood/opencv
output = cv2.connectedComponentsWithStats( · thresh, args["connectivity"], cv2.CV_32S) · (numLabels, labels, stats, centroids) = output · · # loop over the number of unique connected component labels · for i in range(0, numLabels): · # if this is the first component then we examine the ·
Author   ronheywood
🌐
O'Reilly
oreilly.com › library › view › opencv-3-computer › 9781788474443 › ff05a9a2-98d4-4824-bec3-d4cb3ffb7ac0.xhtml
How it works... - OpenCV 3 Computer Vision with Python Cookbook [Book]
March 23, 2018 - There are two functions in OpenCV that can be used to find connected components: cv2.connectedComponents and cv2.connectedComponentsWithStats. Both take the same arguments: the binary image whose components are to be found, the connectivity type, and the depth of the output image, with labels for components.
Authors   Aleksei SpizhevoiAleksandr Rybnikov
Published   2018
Pages   306
🌐
OpenCV
docs.opencv.org › 3.4 › de › d01 › samples_2cpp_2connected_components_8cpp-example.html
OpenCV: samples/cpp/connected_components.cpp
int nLabels = connectedComponents(bw, labelImage, 8); std::vector<Vec3b> colors(nLabels); colors[0] = Vec3b(0, 0, 0);//background ·
🌐
ProgramCreek
programcreek.com › python › example › 89382 › cv2.connectedComponents
Python Examples of cv2.connectedComponents
You may also want to check out all available functions/classes of the module cv2 , or try the search function . ... def acquire_weights(UV_weight_npy): if os.path.isfile(UV_weight_npy): return np.load(UV_weight_npy) else: mask_name = UV_weight_npy.replace('weights.npy', 'mask.png') print(mask_name) UV_mask = imread(mask_name) if UV_mask.ndim == 3: UV_mask = UV_mask[:,:,0] ret, labels = connectedComponents(UV_mask, connectivity=4) unique, counts = np.unique(labels, return_counts=True) print(unique, counts) UV_weights = np.zeros_like(UV_mask).astype(np.float32) for id, count in zip(unique, counts): if id == 0: continue indices = np.argwhere(labels == id) UV_weights[indices[:,0], indices[:,1]] = 1 / count UV_weights *= np.prod(UV_mask.shape) # adjust loss to [0,10] level.
🌐
OpenCV
forum.opencv.org › c++
How to correctly use cv::connectedComponentsWithStats( - C++ - OpenCV
October 18, 2023 - I am a bit confused by the documentation of connectedComponentsWithStats in regards to the stats parameter. According to the docs it is of type OutputArray, so I pass cv::Mat to it, but then I cannot access the individual values as stated in the docs as stats(label, COLUMN) since cv::Mat does not have an operator () that accepts two ints, so what I do instead is stats.at (label, COLUMN), but I am still wondering what type stats should be in order to be able to just do stats(label, COLUMN...
🌐
OpenCV
docs.opencv.org › 3.0-beta › modules › imgproc › doc › structural_analysis_and_shape_descriptors.html
Structural Analysis and Shape Descriptors — OpenCV 3.0.0-dev documentation
Python: cv2.rotatedRectangleIntersection(rect1, rect2) → retval, intersectingRegion¶ · The following values are returned by the function: ... Below are some examples of intersection configurations. The hatched pattern indicates the intersecting region and the red vertices are returned by the function. ... Ask a question on the Q&A forum. If you think something is missing or wrong in the documentation, please file a bug report.
🌐
YouTube
youtube.com › computer vision lab
OPENCV & C++ TUTORIALS - 53 | connectedComponents() - YouTube
This function computes the connected components labeled image of boolean image. It can be very useful and tricky for segmentation methods. It uses an efficie...
Published   September 16, 2022
Views   2K
🌐
Shimat
shimat.github.io › opencvsharp_docs › html › 0a7f101c-c799-953f-ed98-bf260d19c3c4.htm
Cv2.ConnectedComponentsWithAlgorithm Method
Computes the connected components labeled image of boolean image. image with 4 or 8 way connectivity - returns N, the total number of labels[0, N - 1] where 0 represents the background label.ltype specifies the output label image type, an important consideration based on the total number of ...
🌐
Amroamroamro
amroamroamro.github.io › mexopencv › matlab › cv.connectedComponents.html
cv.connectedComponents - mexopencv
cv.connectedComponents - Computes the connected components labeled image of boolean image