【发布时间】:2017-12-15 23:32:25
【问题描述】:
我有一个带有字母和不同颜色形状的图像。我需要对它们执行 kmeans 聚类,然后提供两个不同的图像,一个只重新生成形状,另一个只重新生成字母颜色。 这是一个示例原始图像以及我需要实现的目标。 Original Image
Shape color regenerated 同样,另一个只有白色 R。
我已成功执行 kmeans 聚类算法,如何访问标签和聚类 idx 以重新生成所需的结果?有人可以用示例代码进行说明。这是代码。提前致谢。
import numpy as np
import cv2
img = cv2.imread("/home/manohar/Outputs/Targets/m-0.PNG",1)
cv2.imshow("original",img)
Z = img.reshape((-1,3))
# convert to np.float32
Z = np.float32(Z)
# Here we are applying k-means clustering so that the pixels around a colour are consistent and gave same BGR/HSV values
# define criteria, number of clusters(K) and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
# We are going to cluster with k = 2, because the image will have just two colours ,a white background and the colour of the patch
K = 3
attempts=10
ret,label,center=cv2.kmeans(Z,K,None,criteria,attempts,cv2.KMEANS_PP_CENTERS)
# Now convert back into uint8
#now we have to access the labels to regenerate the clustered image
center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((img.shape))
#res2 is the result of the frame which has undergone k-means clustering
cv2.imshow("res2",res2)
cv2.waitKey()
cv2.destroyAllWindows()
【问题讨论】:
标签: python opencv cluster-analysis k-means image-segmentation