Skip to content

Commit 7639602

Browse files
committed
fixed Kmeans code
1 parent 581f669 commit 7639602

File tree

1 file changed

+5
-7
lines changed

1 file changed

+5
-7
lines changed

machine-learning/kmeans-image-segmentation/kmeans_segmentation.py

+5-7
Original file line numberDiff line numberDiff line change
@@ -14,17 +14,13 @@
1414
# convert to float
1515
pixel_values = np.float32(pixel_values)
1616

17-
print(pixel_values.shape)
1817
# define stopping criteria
1918
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2)
2019

2120
# number of clusters (K)
2221
k = 3
2322
compactness, labels, (centers) = cv2.kmeans(pixel_values, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
2423

25-
print(labels)
26-
print(centers.shape)
27-
2824
# convert back to 8 bit values
2925
centers = np.uint8(centers)
3026

@@ -43,9 +39,11 @@
4339

4440
# disable only the cluster number 2 (turn the pixel into black)
4541
masked_image = np.copy(image)
46-
# convert to the shape of k clusters
47-
masked_image = masked_image.reshape((-1, k))
48-
masked_image[labels == 2] = [0, 0, 0]
42+
# convert to the shape of a vector of pixel values
43+
masked_image = masked_image.reshape((-1, 3))
44+
# color (i.e cluster) to disable
45+
cluster = 2
46+
masked_image[labels == cluster] = [0, 0, 0]
4947

5048
# convert back to original shape
5149
masked_image = masked_image.reshape(image.shape)

0 commit comments

Comments
 (0)