<jupyter_start><jupyter_text>Clustering based unsupervised crack segmentation approach using GLCM texture properties  Preparation of dataset by calculating GLCM textures properties on images to train<jupyter_code>import os
import cv2
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from skimage.feature import greycomatrix, greycoprops
import matplotlib.pyplot as plt
imgpath = r"C:\Users\shubh\Documents\steel_detection\concrete_crack_detection\Positive"
imgs = ["00001.jpg", "00002.jpg", "00003.jpg", "00004.jpg", "00005.jpg", "00006.jpg"]
imgfiles = [os.path.join(imgpath, img) for img in imgs]
imgfiles
# Function to calculate texture properties of a GLCM like correlation, dissimalrity and homogeneity
def GLCM(imgfiles, block=30):
    dissim = []
    correl = []
    homogen = []
    mean = []
    
    for imgfile in imgfiles:
        img = cv2.imread(imgfile, 0)
        (row,col) = img.shape
        for r in range(0,row-block,block):
            for c in range(0,col-block):
                section = img[r:r+block,c:c+block]
                glcm = greycomatrix(section, distances=[5], angles=[0], levels=256,
                            symmetric=True, normed=True)
                
                correl.append(greycoprops(glcm, 'correlation')[0, 0])
                dissim.append(greycoprops(glcm, 'dissimilarity')[0, 0])
                homogen.append(greycoprops(glcm, 'homogeneity')[0, 0])
                mean.append(np.mean(section))
                
    return dissim, correl, homogen
# Calculating texture properties on 10X10 window of image
block = 10
dissim, correl, homogen = GLCM(imgfiles, block)
# Creating dataframe using texture properties
df = pd.DataFrame([])
df['correlation'] = correl
df['dissimilarity'] = dissim
df['homogeneity'] = homogen
df.head()<jupyter_output><empty_output><jupyter_text>Fitting K-means clustering for two clusters (one is cracked region and 2nd is good region)<jupyter_code># K-means clustering to label 2 clusters
kmeans = KMeans(n_clusters=2, init='k-means++', n_init=10, max_iter=1000, random_state=42)
y = kmeans.fit(df)
y.labels_
# Predicted clusters centers
kmeans.cluster_centers_<jupyter_output><empty_output><jupyter_text>Predicting labels on a test image about which model has no imformation<jupyter_code>testimgs = ["00007.jpg"]
testfiles = [os.path.join(imgpath, img) for img in testimgs]
testfiles
dissim_test, correl_test, homogen_test = GLCM(testfiles, block)
df_test = pd.DataFrame([])
df_test['correlation'] = correl_test
df_test['dissimilarity'] = dissim_test
df_test['homogeneity'] = homogen_test
df_test.head()
y_test = kmeans.predict(df_test)
y_test
predict_img = cv2.imread(testfiles[0],0)
img_shape = predict_img.shape
predict_label_img = np.zeros(img_shape)
# Segmenting image based on the labels predicted by K-means clustering algorithm
i = 0
(row,col) = img_shape
for r in range(0,row-block,block):
    for c in range(0,col-block):
        predict_label_img[r:r+block,c:c+block] = y_test[i]
        i += 1
# Plotting original image, predicted image and cleaned image using morpholical operation
_, (ax0, ax1, ax2) = plt.subplots(1, 3, figsize=(8,4))

ax0.axis('off')
ax0.set_title("Image with crack")
ax0.imshow(predict_img, cmap='gray')

ax1.axis('off')
ax1.set_title("Image label using K-means")
ax1.imshow(predict_label_img, cmap='gray')

ax2.axis('off')
ax2.set_title("Post-processed ROI")
ax2.imshow(predict_closing, cmap='gray')

plt.show()
# Finding the contour of cracked region
contours, _ = cv2.findContours(predict_closing.astype(np.uint8), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
len(contours)
# Drawing contours over predicted crack region
output = predict_crack.copy()
predict_crack = cv2.drawContours(cv2.cvtColor(predict_img,cv2.COLOR_GRAY2RGB), contours, -1, (0,255,0),6)
# Plotting the ouput
_, (ax0, ax1) = plt.subplots(1, 2, figsize=(8,4))

ax0.axis('off')
ax0.set_title("Image with crack")
ax0.imshow(predict_img, cmap='gray')

ax1.axis('off')
ax1.set_title("Image with segmented ROI")
ax1.imshow(predict_crack, cmap='gray')

plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12155235538198682, 'fraction_numerical': 0.02928972418843056, 'mean_word_length': 4.691666666666666, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, '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': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '219978', 'license': 'MIT', 'n_tokens_mistral': 1524, 'n_tokens_neox': 1406, 'n_words': 337, 'path': 'crack-segmentation/unsupervised-crack-segmentation.ipynb', 'repo_name': 'shubh-tiwari/unsupervised_crack_segmentation', 'size': '4097'}