<jupyter_start><jupyter_text>Component Labelling Algorithm<jupyter_code>import numpy as np
import matplotlib.pyplot as plt
dim = (20, 20)
img = np.zeros(dim).astype(int)

# shape creation
img[3:10, 2:4] = 1
img[8:10, 2:10] = 1
img[3:10, 9:10] = 1

img[12:14, 11:13] = 1

img[15:19, 15:18] = 1
plt.imshow(img, cmap="Greys")
def component_labelling(inputimp):
    color_map = {}
    label = 1
    
    img = inputimp.copy()
    
    def up(i, j):
        if (i == 0):
            return 0
        else:
            return img[i - 1][j]
        
    def left(i, j):
        if (j == 0):
            return 0
        else:
            return img[i][j - 1]
    
    # First
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            
            if img[i][j] == 0:
                continue
            # new encounter
            if (up(i, j) == 0 and left(i, j) == 0):
                img[i][j] = label
                label += 1
            # top touch
            elif (up(i, j) != 0 and left(i, j) == 0):
                img[i][j] = img[i - 1][j]
            # left touch
            elif (up(i, j) == 0 and left(i, j) != 0):
                img[i][j] = img[i][j - 1]
            # both touch
            else:
            #    if (a != b)
                a = img[i - 1][j]
                b = img[i][j - 1]
                if (a != b):
                    a, b = min(a, b),max(a, b)
                    color_map[b] = a # precomputation for second pass
                img[i][j] = a
    
    # Second
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            
            p = img[i][j]
            
            if p in color_map.keys():
                img[i][j] = color_map[p]
    
    return img
img = component_labelling(img)
color = np.zeros(img.shape + (3,)).astype(int)
colors = { 0: [255, 255, 255] }

for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            
            val = img[i][j]
            
            if val in colors.keys():
                color[i][j]  = colors[val]
            else:
                colors[val] = np.random.randint(0, 255, 3)
                color[i][j]  = colors[val]
plt.imshow(color)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14894571556751907, 'fraction_numerical': 0.037236428891879766, 'mean_word_length': 1.318087318087318, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '599013', 'license': 'MIT', 'n_tokens_mistral': 861, 'n_tokens_neox': 778, 'n_words': 199, 'path': 'all final/Component Labelling.ipynb', 'repo_name': 'parthjain98in/image-processing', 'size': '2229'}