-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbai5_Object_Segmentation.py
More file actions
51 lines (41 loc) · 1.23 KB
/
bai5_Object_Segmentation.py
File metadata and controls
51 lines (41 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 12 12:22:16 2020
@author: phamk
"""
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans
img = mpimg.imread('girl3.jpg')
plt.imshow(img)
imgplot = plt.imshow(img)
plt.axis('off')
plt.show()
X = img.reshape((img.shape[0]*img.shape[1], img.shape[2]))
#cluster = 2,5,10,15,20
for K in [2, 5, 10, 15, 20]:
kmeans = KMeans(n_clusters=K).fit(X)
label = kmeans.predict(X)
img4 = np.zeros_like(X)
# replace each pixel by its center
for k in range(K):
img4[label == k] = kmeans.cluster_centers_[k]
# reshape and display output image
img5 = img4.reshape((img.shape[0], img.shape[1], img.shape[2]))
plt.imshow(img5, interpolation='nearest')
plt.axis('off')
plt.show()
#cluster = 3
for K in [3]:
kmeans = KMeans(n_clusters=K).fit(X)
label = kmeans.predict(X)
img4 = np.zeros_like(X)
# replace each pixel by its center
for k in range(K):
img4[label == k] = kmeans.cluster_centers_[k]
# reshape and display output image
img5 = img4.reshape((img.shape[0], img.shape[1], img.shape[2]))
plt.imshow(img5, interpolation='nearest')
plt.axis('off')
plt.show()