face = sp.face(gray=True)

n_clusters = 5
np.random.seed(0)

X = face.reshape((-1, 1))  # We need an (n_sample, n_feature) array
k_means = cluster.KMeans(n_clusters=n_clusters, n_init=4)
k_means.fit(X)
values = k_means.cluster_centers_.squeeze()
labels = k_means.labels_

# create an array from labels and values
face_compressed = np.choose(labels, values)
face_compressed.shape = face.shape

vmin = face.min()
vmax = face.max()

# original face
plt.figure(1, figsize=(3, 2.2))
plt.imshow(face, cmap=plt.cm.gray, vmin=vmin, vmax=256)

# compressed face
plt.figure(2, figsize=(3, 2.2))
plt.imshow(face_compressed, cmap=plt.cm.gray, vmin=vmin, vmax=vmax)

# equal bins face
regular_values = np.linspace(0, 256, n_clusters + 1)
regular_labels = np.searchsorted(regular_values, face) - 1
regular_values = .5 * (regular_values[1:] + regular_values[:-1])  # mean
regular_face = np.choose(regular_labels.ravel(), regular_values, mode="clip")
    face = sp.face(gray=True)

n_clusters = 5
np.random.seed(0)

X = face.reshape((-1, 1))  # We need an (n_sample, n_feature) array
k_means = cluster.KMeans(n_clusters=n_clusters, n_init=4)
k_means.fit(X)
values = k_means.cluster_centers_.squeeze()
labels = k_means.labels_

# create an array from labels and values
face_compressed = np.choose(labels, values)
face_compressed.shape = face.shape

vmin = face.min()
vmax = face.max()

# original face
plt.figure(1, figsize=(3, 2.2))
plt.imshow(face, cmap=plt.cm.gray, vmin=vmin, vmax=256)

# compressed face
plt.figure(2, figsize=(3, 2.2))
plt.imshow(face_compressed, cmap=plt.cm.gray, vmin=vmin, vmax=vmax)

# equal bins face
regular_values = np.linspace(0, 256, n_clusters + 1)
regular_labels = np.searchsorted(regular_values, face) - 1
regular_values = .5 * (regular_values[1:] + regular_values[:-1])  # mean
regular_face = np.choose(regular_labels.ravel(), regular_values, mode="clip")
Exemplo n.º 3
0
n_clusters = 5
np.random.seed(0)

X = face.reshape((-1, 1))  # 拉成一維向量 (n_sample, n_feature) array
k_means = cluster.KMeans(n_clusters=n_clusters,
                         n_init=4)  # K_means分類,num_cluster=5
k_means.fit(X)
values = k_means.cluster_centers_.squeeze(
)  # 使用不同 centroid seeds 運行 k-means 算法的時間
labels = k_means.labels_

face_compressed = np.choose(labels,
                            values)  #labels範圍0~4,長度768*1024,values代表五個k_keans值
face_compressed.shape = face.shape

v_min = face.min()
v_max = face.max()

plt.figure(1, figsize=(3, 2.2))
plt.imshow(face, cmap=plt.gray())  #原始影像

plt.figure(1, figsize=(3, 2.2))
plt.imshow(face_compressed.reshape(768, 1024), cmap=plt.gray())  #壓縮後影像

regular_values = np.linspace(0, 256, n_clusters + 1)
# 在regular_values(升冪)插入數組face,返回對應位置
regular_labels = np.searchsorted(regular_values, face) - 1
regular_values = 0.5 * (regular_values[1:] + regular_values[:-1])  #mean
regular_face = np.choose(regular_labels.ravel(), regular_values, mode='clip')
regular_face.shape = face.shape
plt.figure(1, figsize=(3, 2.2))