Logo elodees  elodees

A caring AI for a better world













Only alphabetic characters accented or not as well as the space are accepted

Logo IA




Labeling





No account yet ?

Sign up to access all content


Connected Component Labeling

Tested in Anaconda and Python 3.7

# -*- coding: utf-8 -*-
"""
Created on Tue Jun 28 13:21:33 2022
 
@author: Ricore
"""
# Importing the libraries 
import cv2
import numpy as np
from matplotlib import pyplot as plt
 
def showimage(myimage, figsize=[10,10]):
    if (myimage.ndim>2):  #This only applies to RGB or RGBA images (e.g. not to Black and White images)
        myimage = myimage[:,:,::-1] #OpenCV follows BGR order, while matplotlib likely follows RGB order
 
    fig, ax = plt.subplots(figsize=figsize)
    ax.imshow(myimage, cmap = 'gray', interpolation = 'bicubic')
    plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
    plt.show()
 
 
def connected_component_label(path):
 
    # Getting the input image
    img = cv2.imread(path, 0)
    # Converting those pixels with values 1-127 to 0 and others to 1
    img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1]
    # Applying cv2.connectedComponents() 
    num_labels, labels = cv2.connectedComponents(img)
 
    # Map component labels to hue val, 0-179 is the hue range in OpenCV
    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])
 
    # Converting cvt to BGR
    labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)
 
    # set bg label to black
    labeled_img[label_hue==0] = 0
 
 
    # Showing Original Image
    showimage(img)
 
    #Showing Image after Component Labeling
    plt.imshow(cv2.cvtColor(labeled_img, cv2.COLOR_BGR2RGB))
    plt.axis('off')
    plt.title("Image after Component Labeling")
    plt.show()
 
connected_component_label('face.jpg')
connected_component_label('crosses.jpg')
connected_component_label('shapes.png')
 


Connected Component Labeling - GitHub

OpenGenus - GitHub



Connected Component Labeling

Free image provided by pexel.com

Connected Component Labeling

Free image provided by pexel.com


Original image

Free image provided by pexel.com

Connected Component Labeling

Free image provided by pexel.com


Original image

Free image provided by pexel.com

Connected Component Labeling

Free image provided by pexel.com




Image segmentation

Image detection

Image segmentation by instance



Deep learning

Machine learning












Welcome, my name is Eric Soupet and I am the administrator of the site elodees.com. elodees.com is a state of the art of Artificial Intelligence and aims to be collaborative, you can now offer content such as articles, events, tutorials, ... so don't hesitate !

Platform images credit : Pixabay - Pixabay License | Pexels - Pexels License