I have an image with a letter and a shape of different colors. I need to perform kmeans clustering on them and then provide two different images, one with just the shape regenerated and the other with just the Letter color regenerated. Here is a sample original image and what I need to achieve. Original Image
Shape color regenerated And similarly the other one with just the white R.
I have successfully performed kmeans clustering algorithm, How do I access the labels and cluster idx to regenerate the desired results? Can someone please illustrate with a sample code. Here is the code. Thanks in advance.
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()