Skip to content

Commit 52e40dc

Browse files
authored
Add files via upload
1 parent 85fb72c commit 52e40dc

1 file changed

Lines changed: 77 additions & 0 deletions

File tree

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# coding: utf-8
2+
# 2021-05-17 Eastmount CSDN
3+
import cv2
4+
import numpy as np
5+
import matplotlib.pyplot as plt
6+
7+
#读取原始图像
8+
img = cv2.imread('scenery.png')
9+
print(img.shape)
10+
11+
#图像二维像素转换为一维
12+
data = img.reshape((-1,3))
13+
data = np.float32(data)
14+
15+
#定义中心 (type,max_iter,epsilon)
16+
criteria = (cv2.TERM_CRITERIA_EPS +
17+
cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
18+
19+
#设置标签
20+
flags = cv2.KMEANS_RANDOM_CENTERS
21+
22+
#K-Means聚类 聚集成2类
23+
compactness, labels2, centers2 = cv2.kmeans(data, 2, None, criteria, 10, flags)
24+
25+
#K-Means聚类 聚集成4类
26+
compactness, labels4, centers4 = cv2.kmeans(data, 4, None, criteria, 10, flags)
27+
28+
#K-Means聚类 聚集成8类
29+
compactness, labels8, centers8 = cv2.kmeans(data, 8, None, criteria, 10, flags)
30+
31+
#K-Means聚类 聚集成16类
32+
compactness, labels16, centers16 = cv2.kmeans(data, 16, None, criteria, 10, flags)
33+
34+
#K-Means聚类 聚集成64类
35+
compactness, labels64, centers64 = cv2.kmeans(data, 64, None, criteria, 10, flags)
36+
37+
#图像转换回uint8二维类型
38+
centers2 = np.uint8(centers2)
39+
res = centers2[labels2.flatten()]
40+
dst2 = res.reshape((img.shape))
41+
42+
centers4 = np.uint8(centers4)
43+
res = centers4[labels4.flatten()]
44+
dst4 = res.reshape((img.shape))
45+
46+
centers8 = np.uint8(centers8)
47+
res = centers8[labels8.flatten()]
48+
dst8 = res.reshape((img.shape))
49+
50+
centers16 = np.uint8(centers16)
51+
res = centers16[labels16.flatten()]
52+
dst16 = res.reshape((img.shape))
53+
54+
centers64 = np.uint8(centers64)
55+
res = centers64[labels64.flatten()]
56+
dst64 = res.reshape((img.shape))
57+
58+
#图像转换为RGB显示
59+
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
60+
dst2 = cv2.cvtColor(dst2, cv2.COLOR_BGR2RGB)
61+
dst4 = cv2.cvtColor(dst4, cv2.COLOR_BGR2RGB)
62+
dst8 = cv2.cvtColor(dst8, cv2.COLOR_BGR2RGB)
63+
dst16 = cv2.cvtColor(dst16, cv2.COLOR_BGR2RGB)
64+
dst64 = cv2.cvtColor(dst64, cv2.COLOR_BGR2RGB)
65+
66+
#用来正常显示中文标签
67+
plt.rcParams['font.sans-serif']=['SimHei']
68+
69+
#显示图像
70+
titles = [u'原始图像', u'聚类图像 K=2', u'聚类图像 K=4',
71+
u'聚类图像 K=8', u'聚类图像 K=16', u'聚类图像 K=64']
72+
images = [img, dst2, dst4, dst8, dst16, dst64]
73+
for i in range(6):
74+
plt.subplot(2,3,i+1), plt.imshow(images[i], 'gray'),
75+
plt.title(titles[i])
76+
plt.xticks([]),plt.yticks([])
77+
plt.show()

0 commit comments

Comments
 (0)