Obrabotka Metallov 2021 Vol. 23 No. 4

OBRABOTKAMETALLOV Vol. 23 No. 4 2021 29 TECHNOLOGY Приложение 1: 1Программа Appendix 1: 1 Program Программа для кластеризацииK - среднихвPythonвыглядит так , как показано ниже . The program for the k -means clustering inPython 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(“ float”) 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. fit(image) hist = centroid_histogram(clt) bar = plot_colors(hist, clt.cluster_centers_) plt. figure() 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. float32(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. flatten() segmented_image = centers[labels. flatten()] segmented_image = segmented_image.reshape(image1.shape) plt. figure()

RkJQdWJsaXNoZXIy MTk0ODM1