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 - To accomplish this task and to ... two Python scripts: basic_connected_components.py: Demonstrates how to apply connected component labeling, extract each of the components and their statistics, and visualize them on our screen. filtering_connected_components.py: Applies connected component analysis but filters out non-license plate characters by examining each component’s width, height, and area (in pixels). Let’s get started implementing connected component analysis with OpenCV...
🌐
GeeksforGeeks
geeksforgeeks.org › machine learning › python-opencv-connected-component-labeling-and-analysis
Python OpenCV - Connected Component Labeling and Analysis - GeeksforGeeks
July 23, 2025 - Component labeling is basically extracting a region from the original image, except that we try to find only the components which are "connected" which is determined by the application of the graph theory. OpenCV provides us with the following 4 functions for this task: ... The bottom two are more efficient and faster but run only if you have parallel preprocessing with OpenCV enabled, otherwise it's wiser to stick to the first two.
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.

🌐
Medium
medium.com › swlh › image-processing-with-python-connected-components-and-region-labeling-3eef1864b951
Image Processing with Python: Connected Components and Region Labeling | by Jephraim Manansala | The Startup
February 14, 2021 - What are connected components? Basically, it allows us to detect objects with irregular shapes and sizes based on the pixels’ connectivity to their neighbors.
🌐
Data Carpentry
datacarpentry.github.io › image-processing › 08-connected-components.html
Image Processing with Python: Connected Component Analysis
March 20, 2026 - Now, it is your turn to practice. Using the function connected_components, find two ways of printing out the number of objects found in the image.
🌐
Computer Vision
cvexplained.wordpress.com › tag › connected-component-labeling
Connected-component labeling – Computer Vision
June 17, 2020 - Note: OpenCV 3.0 claims to have connected-component support, but I have not tried it out, and I’m unsure if the Python bindings are exposed.
🌐
OpenCV
forum.opencv.org › python
Connected Components returns an error - Python - OpenCV
January 16, 2022 - Hello, everyone! I am trying 2 create a watershed algorithm and encountered a following error: Traceback (most recent call last): File "C:\Users\User\PycharmProjects\pythonProject\main.py", line 15, in ret, marks = cv.connectedComponents(sure_bg) cv2.error: OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\connectedcomponents.cpp:5632: error: (-215:Assertion failed) iDepth == CV_8U || iDepth == CV_8S in function 'cv::connectedComponents_sub1' Here is th...
🌐
OpenCV
forum.opencv.org › python
Is connectedcomponents working right? - Python - OpenCV
February 9, 2022 - I’m working on segmentation at the moment and I want to proof my results with openCV. When I’m working with different connectivity type the result is the same. Is this a bug in openCV? My minimal example with connectivity=4: test = np.zeros((5, 5)).astype(np.uint8) test[1:3, 1:3] = 255 test[3:5, 3:5] = 255 num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(test, 4, cv2.CV_32S) test, labels is: (array([[ 0, 0, 0, 0, 0], [ 0, 255, 255, 0, 0], ...
Find elsewhere
🌐
Biomisa
biomisa.org › wp-content › uploads › 2020 › 02 › Lab 2.pdf pdf
LAB # 02:Basic Image Processing & Connected Component Analysis Lab Objective:
LAB # 02:Basic Image Processing & Connected Component Analysis ... To find this transformation matrix, OpenCV provides a function, cv2.getRotationMatrix2D.
🌐
Hackster.io
hackster.io › adam-taylor › fpga-vision-lab-real-time-frame-grabbing-streaming-047239
FPGA Vision Lab: Real-Time Frame Grabbing & Streaming - Hackster.io
April 7, 2026 - Grabbing the frames or displaying and controlling streaming frames is controlled by a Python application running on a client PC. The project is built around a MicroBlaze V processor, the processor itself is connected to the following IP cores.
🌐
NiceGUI
nicegui.io
NiceGUI
NiceGUI is an easy-to-use, Python-based UI framework, which shows up in your web browser. You can create buttons, dialogs, Markdown, 3D scenes, plots and much more.
🌐
O'Reilly
oreilly.com › library › view › opencv-3-computer › 9781788474443 › 736eb842-451e-43f1-8f88-c8852b1168e9.xhtml
Extracting connected components from a binary image - OpenCV 3 Computer Vision with Python Cookbook [Book]
March 23, 2018 - Extracting connected components from a binary image Connected components in binary images are areas of non-zero values. Each element of each connected component is surrounded by at...
Authors   Aleksei SpizhevoiAleksandr Rybnikov
Published   2018
Pages   306
🌐
O'Reilly
oreilly.com › library › view › learn-opencv-4 › 9781789341225 › 3f4b3c3d-1390-4e98-bb5c-3f22d6d793c1.xhtml
The connected components algorithm - Learn OpenCV 4 by Building Projects - Second Edition [Book]
November 30, 2018 - The connected component algorithm is a very common algorithm that's used to segment and identify parts in binary images. The connected component is an iterative algorithm with the purpose of labeling an image using eight or four connectivity pixels.
Authors   David Millán EscriváVinícius G. Mendonça
Published   2018
Pages   310
🌐
Medium
medium.com › @h.shaig93 › connected-component-analysis-implementing-from-scratch-with-python-c5931785493b
Implementing Connected Component Analysis for Image Processing from Scratch with Python | by Shaig Hamzaliyev | Medium
April 6, 2024 - Implementing Connected Component Analysis for Image Processing from Scratch with Python In this article I will try to give some intuitive introduction to connected component analysis (CCA). In this …
🌐
PyPI
pypi.org › project › connected-components-3d
connected-components-3d 4.0.0
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
Kaggle
kaggle.com › code › fazela › dip-lab-03-connected-component-analysis
Dip_lab_03: Connected Component Analysis
October 23, 2023 - Explore and run AI code with Kaggle Notebooks | Using data from image used in dip_lab_03
🌐
Scaler
scaler.com › home › topics › connected component analysis in image processing
Connected Component Analysis in Image Processing - Scaler Topics
December 18, 2023 - Connected component analysis is a powerful technique for identifying and analyzing connected regions and objects in images. It has many applications in computer vision and image processing, including object detection, segmentation, tracking, and recognition. By using OpenCV and appropriate ...
🌐
RUTUBE
rutube.ru › video › 0435b3118d775183eee99a15c07576ae
Text Detection through Morphology & Connected Component Labeling | Image Processing, Python OpenCV
Text Detection through Morphology & Connected Component Labeling | Image Processing, Python OpenCV How to count number of lines in an image How to count number of words in an image How to detect text in an image How to apply connected component labelling (CC Labeling) on in image. How to color the connected components Issue solution: Connected components labeling is giving wrong number of components 0:00 Intro 2:42 Code for text detection (merging/counting Lines) 5:06 Code for CC Labeling 6:49 Solution for Issue: Wrong number of labels returned by CC labeling 8:54 Display connected components in different colors 12:12 Code for text detection (merging/counting Words)Показать целиком
Published   December 2, 2023
Views   17
🌐
GitHub
github.com › opencv › opencv_contrib › issues › 3472
How do I get the center of connectedComponents with cuda ? · Issue #3472 · opencv/opencv_contrib
April 18, 2023 - I'm working on connected component analysis using OpenCV-CUDA, and I want to use the API 'cv2.cuda.labelComponents'. According to the official documentation of OpenCV 4.7.0, this API should exist. However, when I try to use it in Python, I get an attribute error.
Author   opencv