Skip to content

Commit 2ca45cb

Browse files
authored
Add files via upload
1 parent ab445a3 commit 2ca45cb

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# coding: utf-8
2+
# BY:Eastmount CSDN 2021-08-20
3+
import cv2
4+
import numpy as np
5+
import matplotlib.pyplot as plt
6+
7+
#读取原始图像
8+
img = cv2.imread('nv.png')
9+
10+
#图像二维像素转换为一维
11+
data = img.reshape((-1,3))
12+
data = np.float32(data)
13+
14+
#定义中心 (type,max_iter,epsilon)
15+
criteria = (cv2.TERM_CRITERIA_EPS +
16+
cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
17+
18+
#设置标签
19+
flags = cv2.KMEANS_RANDOM_CENTERS
20+
21+
#K-Means聚类 聚集成4类
22+
compactness, labels, centers = cv2.kmeans(data, 4, None, criteria, 10, flags)
23+
24+
25+
#图像转换回uint8二维类型
26+
centers = np.uint8(centers)
27+
res = centers[labels.flatten()]
28+
dst = res.reshape((img.shape))
29+
30+
#图像转换为RGB显示
31+
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
32+
dst = cv2.cvtColor(dst, cv2.COLOR_BGR2RGB)
33+
34+
#用来正常显示中文标签
35+
plt.rcParams['font.sans-serif']=['SimHei']
36+
37+
#显示图像
38+
titles = ['原始图像', '聚类量化 K=4']
39+
images = [img, dst]
40+
for i in range(2):
41+
plt.subplot(1,2,i+1), plt.imshow(images[i], 'gray'),
42+
plt.title(titles[i])
43+
plt.xticks([]),plt.yticks([])
44+
plt.show()

0 commit comments

Comments
 (0)