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.

Answer from Zack Knopp on Stack Overflow
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 :)

🌐
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...
Discussions

python - Get stats from specific Connected Components with opencv (with mask) - Stack Overflow
I am new to opencv (python) and don't really know how to tackle my new task. I have several images (binarized) and masks for them. I want to extract all Connected Components of the original image ... More on stackoverflow.com
🌐 stackoverflow.com
How to use openCV's connected components with stats in python?
How to use openCV's connected components with stats in python?I am looking for an example of how to use OpenCV's More on exchangetuts.com
🌐 exchangetuts.com
1
919
March 7, 2016
python - opencv connectedComponentsWithStats - Stack Overflow
first post here! I just installed python-opencv. According to python my version is: >>> import cv2 >>> cv2.__version__ '2.4.8' My Ubuntu version is 14.04. I then started a python- More on stackoverflow.com
🌐 stackoverflow.com
OpenCV Python cv2.connectedComponentsWithStats - Stack Overflow
Is it by design that you must pass cv2.connectedComponentsWithStats a white-on-black image as opposed to a black-on-white image? I get different results doing one versus the other. Example Code: ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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. Both the first and the second methods are the same except in the second method, as the name suggests, we get stats for each of the components, and we'll use the second method because in most cases you're going to need those stats.
🌐
OpenCV
docs.opencv.org › 3.4 › d3 › dc0 › group__imgproc__shape.html
OpenCV: Structural Analysis and Shape Descriptors
computes the connected components labeled image of boolean image and also produces a statistics output for each label · 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, ...
🌐
ProgramCreek
programcreek.com › python › example › 89340 › cv2.connectedComponentsWithStats
Python Examples of cv2.connectedComponentsWithStats
sizes = stats[1:, -1] nb_components = nb_components - 1 # your answer image img2 = img # for every component in the image, you keep it only if it's above min_size for i in range(0, nb_components): if sizes[i] < min_size: img2[output == i + 1] = 0 return img2 ... def removeSmallComponents(image, threshold): #find all your connected components (white blobs in your image) nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(image, connectivity=8) sizes = stats[1:, -1]; nb_components = nb_components - 1 img2 = np.zeros((output.shape),dtype = np.uint8) #for every component in the image, you keep it only if it's above threshold for i in range(0, nb_components): if sizes[i] >= threshold: img2[output == i + 1] = 255 return img2
🌐
pythontutorials
pythontutorials.net › blog › how-to-use-opencv-s-connectedcomponentswithstats-in-python
How to Use OpenCV's connectedComponentsWithStats in Python: Step-by-Step Example (OpenCV 3+) — pythontutorials.net
OpenCV’s connectedComponentsWithStats is an extension of the basic connectedComponents function. It not only labels connected components but also returns statistical information about each component, making it easier to filter or analyze objects.
🌐
YouTube
youtube.com › how to fix your computer
PYTHON : How to use openCV's connected components with stats in python? - YouTube
PYTHON : How to use openCV's connected components with stats in python? [ Gift : Animated Search Engine : https://www.hows.tech/p/recommended.html ] PYTHON ...
Published   December 8, 2021
Views   1K
Find elsewhere
🌐
DNMTechs
dnmtechs.com › using-opencvs-connectedcomponentswithstats-in-python-3
Using OpenCV’s connectedComponentsWithStats in Python 3 – DNMTechs – Sharing and Storing Technology Knowledge
The connectedComponentsWithStats function in OpenCV is used to find connected components in a binary image. It returns the number of labels, the labeled image, the statistics of each connected component, and the centroid of each component.
🌐
GitHub
github.com › ronheywood › opencv › blob › main › basic-connected-components.py
opencv/basic-connected-components.py at main · ronheywood/opencv
area = stats[i, cv2.CC_STAT_AREA] · (cX, cY) = centroids[i] · · # clone our original image (so we can draw on it) and then draw · # a bounding box surrounding the connected component along with · # a circle corresponding to the centroid ·
Author   ronheywood
🌐
Stack Overflow
stackoverflow.com › questions › 57982903 › get-stats-from-specific-connected-components-with-opencv-with-mask
python - Get stats from specific Connected Components with opencv (with mask) - Stack Overflow
Maybe I was unclear: I'd like to know the ratio of length to height and would like a mean of this ratio over all selected components. So I want something like: "Component A is 75 (rows) by 450 (columns)." ... The stats return variable for cv.connectedComponentsWithStats includes cv.CC_STAT_LEFT, cv.CC_STAT_TOP, cv.CC_STAT_WIDTH and cv.CC_STAT_HEIGHT.
🌐
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 - cv2.connectedComponents is simpler, ... outputs, cv2.connectedComponentsWithStats also returns statistics about each component and the components' centroid locations....
Authors   Aleksei SpizhevoiAleksandr Rybnikov
Published   2018
Pages   306
🌐
Shimat
shimat.github.io › opencvsharp_docs › html › 1baab192-4d4f-0359-33a3-32ec20b8a721.htm
Cv2.ConnectedComponentsWithStats Method (InputArray, OutputArray, OutputArray, OutputArray, PixelConnectivity, MatType)
public: static int ConnectedComponentsWithStats( InputArray^ image, OutputArray^ labels, OutputArray^ stats, OutputArray^ centroids, PixelConnectivity connectivity, MatType ltype )
🌐
OpenCV Q&A Forum
answers.opencv.org › question › 168281 › calculating-image-moments-after-connected-component-labeling-function
Calculating image moments after connected component labeling function - OpenCV Q&A Forum
July 20, 2017 - # for every component in the output image for label in range(num_labels): # retrieving the width of the bounding box of the component width = stats[label, cv2.CC_STAT_WIDTH] # retrieving the height of the bounding box of the component height = stats[label, cv2.CC_STAT_HEIGHT] # retrieving the leftmost coordinate of the bounding box of the component x = stats[label, cv2.CC_STAT_LEFT] # retrieving the topmost coordinate of the bounding box of the component y = stats[label, cv2.CC_STAT_TOP] # creating the ROI using indexing roi = thresh[y:y+height, x:x+width] # calculating the image moments and Hu moments of the ROI img_moments = cv2.moments(roi) hu = cv2.HuMoments(img_moments) I’m sure there are other approaches for segmenting the connected components in an input image, but at the moment this one is doing the work for me.
🌐
OpenCV Q&A Forum
answers.opencv.org › question › 194566 › removing-noise-using-connected-components
removing noise using connected components - OpenCV Q&A Forum
I have been indeed trying a similar approach with connectedStats method, but using Python. Sorry, that I didnt mention it before. Anyway, here is what Im trying, but the mask Image always seems to be just zeros.` nlabel,labels,stats,centroids = cv2.connectedComponentsWithStats(img,connectivity=8) mask = np.zeros_like(labels,dtype=np.uint8) for l in range(1,nlabel): if stats[l,cv2.CC_STAT_AREA]<=1000: labels_small.append(l) mask[labels == labels_small] = 255 cv2.imwrite('mask.jpg',mask)
🌐
GitHub
github.com › opencv › opencv-python › issues › 602
cv2.connectedComponentsWithStats raises weird error on latest version · Issue #602 · opencv/opencv-python
December 29, 2021 - nLabels, labels, stats, centroids = cv2.connectedComponentsWithStats(text_score_comb.astype(np.uint8), connectivity=4) cv2.error: Unknown C++ exception from OpenCV code · Took me a long time to figure out what's wrong because of the vague error message... Finally solved it by switching back to version 4.5.4.60 · Windows 10 64bit opencv-python 4.5.5.62 Use the cv2.connectedComponentsWithStats function with the latest opencv-python version
Author   opencv
🌐
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 ...
Top answer
1 of 1
125

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.