Home > Net >  How can I change the color of kmeans clusters in image segmentation
How can I change the color of kmeans clusters in image segmentation

Time:01-27

I tried to perform image segmentation using kmeans clustering.

I want to have control concerning the color of classes.How i can do that ?

            # convert to np.float32
            Z = np.float32(Z)

            # define criteria, number of clusters(K) and apply kmeans()
            criteria = (cv2.TERM_CRITERIA_EPS   cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
            K = 2
            ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)

            # Now convert back into uint8, and make original image
            center = np.uint8(center)
            res = center[label.flatten()]
            res2 = res.reshape((img.shape))

            #cv2.imshow('res2',res2)
            #cv2.waitKey(0)
            #cv2.destroyAllWindows()

            Image.fromarray(res2).save(f   'kmeans.png', "png", quality=100)     
kmean()

CodePudding user response:

I don't know what you want to control with 2 centers.
If you want to get binary map, you can follow here:

# convert to np.float32
Z = np.float32(Z)

# define criteria, number of clusters(K) and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS   cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 2
ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)

# get the most popular color and specify it is black
black_color = np.argmax(np.bincount(label.flatten()))

# generate binary map with white color
center = np.ones((K,1), dtype = 'uint8') * 255
center[black_color] = [0]
res = center[label.flatten()]
res2 = res.reshape((image_text.shape[0], image_text.shape[1], 1))

return res2

You can change any color you want, not just white and black. Hope to help you

  •  Tags:  
  • Related