Python图像识别(聚类)

 1 # -*- coding: utf-8 -*-
 2 """
 3 Created on Fri Sep 21 15:37:26 2018
 4 
 5 @author: zhen
 6 """
 7 from PIL import Image
 8 import numpy as np
 9 from sklearn.cluster import KMeans
10 import matplotlib
11 import matplotlib.pyplot as plt
12 
13 def restore_image(cb, cluster, shape):
14     row, col, dummy = shape
15     image = np.empty((row, col, dummy))
16     for r in range(row):
17         for c in range(col):
18             image[r, c] = cb[cluster[r * col + c]]
19     return image
20 
21 def show_scatter(a):
22     N = 10
23     density, edges = np.histogramdd(a, bins=[N, N, N], range=[(0, 1), (0, 1), (0, 1)])
24     density /= density.max()
25     x = y = z = np.arange(N)
26     d = np.meshgrid(x, y, z)
27     
28     fig = plt.figure(1, facecolor='w')
29     ax = fig.add_subplot(111, projection='3d')
30 
31     cm = matplotlib.colors.ListedColormap(list('rgbm'))
32     ax.scatter(d[0], d[1], d[2], s=100 * density, cmap=cm, marker='o', depthshade=True)
33     ax.set_xlabel(u'')
34     ax.set_ylabel(u'绿')
35     ax.set_zlabel(u'')
36     plt.title(u'图像颜色三维频数分布', fontsize=20)
37     
38     plt.figure(2, facecolor='w')
39     den = density[density > 0]
40     den = np.sort(den)[::-1]
41     t = np.arange(len(den))
42     plt.plot(t, den, 'r-', t, den, 'go', lw=2)
43     plt.title(u'图像颜色频数分布', fontsize=18)
44     plt.grid(True)
45     
46     plt.show()
47       
48 if __name__ == '__main__':
49     matplotlib.rcParams['font.sans-serif'] = [u'SimHei']
50     matplotlib.rcParams['axes.unicode_minus'] = False
51     # 聚类数2,6,30
52     num_vq = 2
53     im = Image.open('C:/Users/zhen/.spyder-py3/images/Lena.png')
54     image = np.array(im).astype(np.float) / 255
55     image = image[:, :, :3]
56     image_v = image.reshape((-1, 3))
57     kmeans = KMeans(n_clusters=num_vq, init='k-means++')
58     show_scatter(image_v)
59     
60     N = image_v.shape[0]  # 图像像素总数
61     # 选择样本,计算聚类中心
62     idx = np.random.randint(0, N, size=int(N * 0.7))
63     image_sample = image_v[idx]
64     kmeans.fit(image_sample)
65     result = kmeans.predict(image_v)  # 聚类结果
66     print('聚类结果:\n', result)
67     print('聚类中心:\n', kmeans.cluster_centers_)
68     
69     plt.figure(figsize=(15, 8), facecolor='w')
70     plt.subplot(211)
71     plt.axis('off')
72     plt.title(u'原始图片', fontsize=18)
73     plt.imshow(image)
74     # plt.savefig('原始图片.png')
75     
76     plt.subplot(212)
77     vq_image = restore_image(kmeans.cluster_centers_, result, image.shape)
78     plt.axis('off')
79     plt.title(u'聚类个数:%d' % num_vq, fontsize=20)
80     plt.imshow(vq_image)
81     # plt.savefig('矢量化图片.png')
82     
83     plt.tight_layout(1.2)
84     plt.show()

结果:

      

  1.当k=2时:

  

       

  2.当k=6时:

    

        

  3.当k=30时:

    

       

总结:当聚类个数较少时,算法运算速度快但效果较差,当聚类个数较多时,运算速度慢效果好但容易过拟合,所以恰当的k值对于聚类来说影响极其明显!!

 

转载于:https://www.cnblogs.com/yszd/p/9687897.html

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Fuzzy Cluster Analysis -Methods for Classification,Data Analysis and Image Recognition Frank Hoppner, Frank Klawonn, Rudolf Kruse,Thomas Runkler 著 目录 1 Basic Concepts 1.1 Analysis of data 1.2 Cluster analysis 1.3 Objective functilm-based cluster analysis 1.5 Special objective functions 1.6 A principal clustering algorithm 1. 7 Unknown number of clusters problem 2 Classical Fuzzy Clustering Algorithms 2.1 The fuzzy c-means algorithm 2.2 The Gustafson-Kessel algorithm 2.3 The Gath-Geva algorithm 2.4 Simplified versions of GK and GG 2.5 Computational effort 3 Linear and Ellipsoidal Prototypes 3.1 The fuzzy c-varieties algorithm 3.2 The adaptive fuzzy clustering algorithm 3.3 Algorithms by Gustafson/Kessel and Gath/ Geva 3.4 Computational effort 4 Shell Prototypes 4.1 The fuzzy c-shells algorithm 4.2 The fuzzy c-spherical shells algorithm 4.3 The adaptive fuzzy. c-shells algorithm 4.4 The fuzzy c-ellipsoidal shells algorithm 4.5 The fuzzy c-ellipses algorithm 4.6 The fuzzy c-quadric shells algorithm 4.7 The modified FCQS algorithm 4.8 Computational effort 5 Polygonal Object Boundaries 5.1 Detection of rectangles 5.2 The fuzzy c-rectangular shells algorithm 5.3 The fuzzy c-2-rectangular sl}ells algorithm 5.4 Computational effort 6 Cluster Estimation Models 6.1 AO membership functions 6.2 ACE membership functions 6.3 Hyperconic clustering (dancing cones) 6.4 Ptototype defuzzification. 6.5 ACE for higher-order prototypes 6.6 Acceleration of the Clustering Process 6.6.1 Fast Alternating Cluster Estimation (F.-\CE) 6.6.2 Regular Alternating Cluster Estimation (rACE) 6. 7 Comparison: AO and ACE 7 Cluster Validity 7.1 Global validity measures 7.1.1 Solid clustering validity measures 7.1.2 Shell clustering validity measures 7.2 Local validity measures 7.2.1 The compatible cluster merging algorithm 7.2.2 The unsupervised FCSS algorithm 7.2.3 The contour density criterion 7.2.4 The unsupervised (M)FCQS algorithm 7.3 Initialization by edge detection 8 Rule Generation with Clustering 8.1 From membership matrices to membership functions 8.1.1 Interpolation 8.1.2 Projection and cylindrical extension 8.1.3 Convex completion 8.1.4 Approximation 8.1.5 Cluster estimation with ACE 8.2 Rules for fuzzy classifiers 8.2.1 Input space clustering 8.2.2 Cluster projection 8.2.3 Input output product space clustering 8.3 Rules for function approximation 8.3.1 Input ouput product space clustering 8.3.2 Input space clustering 8.3.3 Output space clustering 8.4 Choice of the clustering domain Appendix A.1 Notation A.2 Influence of scaling on the cluster partition A.3 Overview on FCQS cluster shapes A.4 Transformation to straight lines References Index
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值