Application of digital image processing technique in the microstructure analysis and the machinability investigation

OBRABOTKAMETALLOV Том 23 № 4 2021 TECHNOLOGY Appendix: 1 Program The program for the k-means clustering in Python is as under. import cv2 import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans def centroid_histogram(clt): # grab the number of different clusters and create a histogram # based on the number of pixels assigned to each cluster numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1) (hist, _) = np.histogram(clt.labels_, bins = numLabels) # normalize the histogram, such that it sums to one hist = hist.astype(“ fl oat”) hist /= hist.sum() # return the histogram return hist def plot_colors(hist, centroids): bar = np.zeros((50, 300, 3), dtype = “uint8”) startX = 0 for (percent, color) in zip(hist, centroids): print(‘Color = ‘, color) print(‘Percentage = ‘,”%.2f” % (percent*100)) endX = startX + (percent * 300) cv2.rectangle(bar, (int(startX), 0), (int(endX), 50),color.astype(“uint8”).tolist(), -1) startX = endX return bar k = 2 image_image = ‘0.5.jpg’ image = cv2.imread(image_image) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = image.reshape((image.shape[0] * image.shape[1], 3)) clt = KMeans(n_clusters = k) clt. fi t(image) hist = centroid_histogram(clt) bar = plot_colors(hist, clt.cluster_centers_) plt. fi gure() plt.axis(“off”) plt.imshow(bar) plt.show() image1 = cv2.imread(image_image) image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB) pixel_values = image1.reshape((-1, 3)) pixel_values = np. fl oat32(pixel_values) criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2) _, labels, (centers) = cv2.kmeans(pixel_values, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) centers = np.uint8(centers) labels = labels. fl atten() segmented_image = centers[labels. fl atten()] segmented_image = segmented_image.reshape(image1.shape) plt. fi gure()

RkJQdWJsaXNoZXIy MTk0ODM1