【发布时间】:2019-02-02 08:08:58
【问题描述】:
我正在对希望分类的图像运行 kmeans 聚类。当我运行程序时,我得到了相同的结果,期望我的颜色不一致,这意味着 kmeans 没有重复完全相同的过程。每次执行程序时,如何使类保持相同?
这里有两个例子。集合中的第一张图片是kmeans聚类结果,第二张是图片上的分类图。
代码:
#Set a 6 KMeans clustering
kmeans = KMeans(n_clusters = 4, n_jobs = -2)
#Compute cluster centers and predict cluster indices
X_clustered = kmeans.fit_predict(x_3d)
# Display scatter of kmeans
plt.scatter(X[:, 0], X[:, 1], c=X_clustered, s=5, cmap='viridis')
plt.show()
# Create a temp dataframe from our PCA projection data "x_3d"
df = pd.DataFrame(x_3d)
df['X_cluster'] = X_clustered
#create an greyscale image and remap the color pixel based on the df file given
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
tempImage = img
row,col = img.shape[:2]
count = 0
for i in range(row):
for j in range(col):
if X_clustered[count]==0:
tempImage[i,j] = (255,255,255,1)
elif X_clustered[count]==1:
tempImage[i,j] = (0,255,0,1)
elif X_clustered[count]==2:
tempImage[i,j] = (0,0,255,1)
elif X_clustered[count]==3:
tempImage[i,j] = (125,125,0,1)
elif X_clustered[count]==4:
tempImage[i,j] = (0,125,125,1)
elif X_clustered[count]==5:
tempImage[i,j] = (125,0,125,1)
elif X_clustered[count]==6:
tempImage[i,j] = (255,255,0,1)
elif X_clustered[count]==7:
tempImage[i,j] = (255,0,255,1)
elif X_clustered[count]==8:
tempImage[i,j] = (0,255,255,1)
elif X_clustered[count]==9:
tempImage[i,j] = (125,125,125)
count+= 1
return tempImage
【问题讨论】: