k means clustering and disabling clusters

Solutions on MaxInterview for k means clustering and disabling clusters by the best coders in the world

showing results for - "k means clustering and disabling clusters"
Amandine
24 Apr 2018
1img = path
2img = cv2.imread(img)
3img = cv2.cvtColor(img,cv2.COLOR_BGR2LAB)
4pixVal = img.reshape((-1,3))
5pixVal = np.float(pixVal)
6criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2)
7# number of clusters (K)
8k = 3
9_, labels, (centers) = cv2.kmeans(pixVal, k, None,
10                                  criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
11# convert back to 8 bit values
12centers = np.uint8(centers)
13
14# flatten the labels array
15labels = labels.flatten()
16
17# convert all pixels to the color of the centroids
18segmented_image = centers[labels.flatten()]
19# reshape back to the original image dimension
20segmented_image = segmented_image.reshape(image.shape)
21# show the image
22plt.imshow(segmented_image)
23plt.show()
24
25# disable only the cluster number 2 (turn the pixel into black)
26masked_image = np.copy(image)
27# convert to the shape of a vector of pixel values
28masked_image = masked_image.reshape((-1, 3))
29# color (i.e cluster) to disable
30cluster = 2
31masked_image[labels == cluster] = [0, 0, 0]
32# convert back to original shape
33masked_image = masked_image.reshape(image.shape)
34# show the image
35plt.imshow(masked_image)
36plt.show()
37