Skip to content

Commit a30867a

Browse files
authored
Create blog19-image01.py
1 parent bba0945 commit a30867a

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

blog19-kmeans/blog19-image01.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# coding: utf-8
2+
import cv2
3+
import numpy as np
4+
import matplotlib.pyplot as plt
5+
6+
#读取原始图像灰度颜色
7+
img = cv2.imread('scenery.png', 0)
8+
print img.shape
9+
10+
#获取图像高度、宽度
11+
rows, cols = img.shape[:]
12+
13+
#图像二维像素转换为一维
14+
data = img.reshape((rows * cols, 1))
15+
data = np.float32(data)
16+
17+
#定义中心 (type,max_iter,epsilon)
18+
criteria = (cv2.TERM_CRITERIA_EPS +
19+
cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
20+
21+
#设置标签
22+
flags = cv2.KMEANS_RANDOM_CENTERS
23+
24+
#K-Means聚类 聚集成4类
25+
compactness, labels, centers = cv2.kmeans(data, 4, None, criteria, 10, flags)
26+
27+
#生成最终图像
28+
dst = labels.reshape((img.shape[0], img.shape[1]))
29+
30+
#用来正常显示中文标签
31+
plt.rcParams['font.sans-serif']=['SimHei']
32+
33+
#显示图像
34+
titles = [u'原始图像', u'聚类图像']
35+
images = [img, dst]
36+
for i in xrange(2):
37+
plt.subplot(1,2,i+1), plt.imshow(images[i], 'gray'),
38+
plt.title(titles[i])
39+
plt.xticks([]),plt.yticks([])
40+
plt.show()

0 commit comments

Comments
 (0)