# -*- coding: utf-8 -*-
"""
Created on Fri Sep 21 15:37:26 2018 @author: zhen
"""
from PIL import Image
import numpy as np
from sklearn.cluster import KMeans
import matplotlib
import matplotlib.pyplot as plt def restore_image(cb, cluster, shape):
row, col, dummy = shape
image = np.empty((row, col, dummy))
for r in range(row):
for c in range(col):
image[r, c] = cb[cluster[r * col + c]]
return image def show_scatter(a):
N = 10
density, edges = np.histogramdd(a, bins=[N, N, N], range=[(0, 1), (0, 1), (0, 1)])
density /= density.max()
x = y = z = np.arange(N)
d = np.meshgrid(x, y, z) fig = plt.figure(1, facecolor='w')
ax = fig.add_subplot(111, projection='3d') cm = matplotlib.colors.ListedColormap(list('rgbm'))
ax.scatter(d[0], d[1], d[2], s=100 * density, cmap=cm, marker='o', depthshade=True)
ax.set_xlabel(u'红')
ax.set_ylabel(u'绿')
ax.set_zlabel(u'蓝')
plt.title(u'图像颜色三维频数分布', fontsize=20) plt.figure(2, facecolor='w')
den = density[density > 0]
den = np.sort(den)[::-1]
t = np.arange(len(den))
plt.plot(t, den, 'r-', t, den, 'go', lw=2)
plt.title(u'图像颜色频数分布', fontsize=18)
plt.grid(True) plt.show() if __name__ == '__main__':
matplotlib.rcParams['font.sans-serif'] = [u'SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False
# 聚类数2,6,30
num_vq = 2
im = Image.open('C:/Users/zhen/.spyder-py3/images/Lena.png')
image = np.array(im).astype(np.float) / 255
image = image[:, :, :3]
image_v = image.reshape((-1, 3))
kmeans = KMeans(n_clusters=num_vq, init='k-means++')
show_scatter(image_v) N = image_v.shape[0] # 图像像素总数
# 选择样本,计算聚类中心
idx = np.random.randint(0, N, size=int(N * 0.7))
image_sample = image_v[idx]
kmeans.fit(image_sample)
result = kmeans.predict(image_v) # 聚类结果
print('聚类结果:\n', result)
print('聚类中心:\n', kmeans.cluster_centers_) plt.figure(figsize=(15, 8), facecolor='w')
plt.subplot(211)
plt.axis('off')
plt.title(u'原始图片', fontsize=18)
plt.imshow(image)
# plt.savefig('原始图片.png') plt.subplot(212)
vq_image = restore_image(kmeans.cluster_centers_, result, image.shape)
plt.axis('off')
plt.title(u'聚类个数:%d' % num_vq, fontsize=20)
plt.imshow(vq_image)
# plt.savefig('矢量化图片.png') plt.tight_layout(1.2)
plt.show()

结果:

      

  1.当k=2时:

  

      

  2.当k=6时:

   

        

  3.当k=30时:

   

       

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

Python图像识别(聚类)的更多相关文章

  1. 机器学习:Python实现聚类算法(三)之总结

    考虑到学习知识的顺序及效率问题,所以后续的几种聚类方法不再详细讲解原理,也不再写python实现的源代码,只介绍下算法的基本思路,使大家对每种算法有个直观的印象,从而可以更好的理解函数中参数的意义及作 ...

  2. 听说图像识别很难,大神十行代码进行Python图像识别

      随着深度学习算法的兴起和普及,人工智能领域取得了令人瞩目的进步,特别是在计算机视觉领域.21世纪的第二个十年迅速采用卷积神经网络,发明了最先进的算法,大量训练数据的可用性以及高性能和高性价比计算的 ...

  3. python 图像识别

    这是一个最简单的图像识别,将图片加载后直接利用Python的一个识别引擎进行识别 将图片中的数字通过 pytesseract.image_to_string(image)识别后将结果存入到本地的txt ...

  4. Python机器学习--聚类

    K-means聚类算法 测试: # -*- coding: utf-8 -*- """ Created on Thu Aug 31 10:59:20 2017 @auth ...

  5. python图像识别--验证码

    1.pip3 install pyocr 2.pip3 install pillow or easy_install Pillow 3.安装tesseract-ocr:http://jaist.dl. ...

  6. 机器学习:Python实现聚类算法(一)之K-Means

    1.简介 K-means算法是最为经典的基于划分的聚类方法,是十大经典数据挖掘算法之一.K-means算法的基本思想是:以空间中k个点为中心进行聚类,对最靠近他们的对象归类.通过迭代的方法,逐次更新各 ...

  7. 机器学习:Python实现聚类算法(一)之AP算法

    1.算法简介 AP(Affinity Propagation)通常被翻译为近邻传播算法或者亲和力传播算法,是在2007年的Science杂志上提出的一种新的聚类算法.AP算法的基本思想是将全部数据点都 ...

  8. Python实现聚类算法AP

    1.算法简介 AP(Affinity Propagation)通常被翻译为近邻传播算法或者亲和力传播算法,是在2007年的Science杂志上提出的一种新的聚类算法.AP算法的基本思想是将全部数据点都 ...

  9. 机器学习:Python实现聚类算法(二)之AP算法

    1.算法简介 AP(Affinity Propagation)通常被翻译为近邻传播算法或者亲和力传播算法,是在2007年的Science杂志上提出的一种新的聚类算法.AP算法的基本思想是将全部数据点都 ...

随机推荐

  1. WTF小程序之<web-view>

    叨叨两句 昨天爬了一下午坑才出来的我向大家问好

  2. 修改vs2012 颜色

    http://bbs.pcbeta.com/viewthread-1265615-1-1.html VS2012的默认深色主题的确让整个IDE看起来很有气场,而且深色的主题保护眼睛,还是蛮不错的. 但 ...

  3. 详解C#泛型(一)

    一.C#中的泛型引入了类型参数的概念,类似于C++中的模板,类型参数可以使类型或方法中的一个或多个类型的指定推迟到实例化或调用时,使用泛型可以更大程度的重用代码.保护类型安全性并提高性能:可以创建自定 ...

  4. MyCAT 源码解析 —— 分片结果合并(使用unsaferow)

    1. 概述 2. 多分片执行 SQL 3. 合并多分片结果 3.1 记录头(header) 3.2 记录行(row) 3.1 AbstractDataNodeMerge 3.2 DataNodeMer ...

  5. 命令行下更好显示 postgresql 的查询结果

    之前在用 mysql 的时候发现,当列数特别多的时候,在 linux 命令行下,显示不太友好, 然后可以通过将 sql 末尾的 “:” 改为 “\G” 来处理,详情看 命令行下更好显示 mysql 查 ...

  6. LVS+keepalived+nginx+tomcat部署实现

    拓扑如下所示 # 节点分布情况 LVS-dr-master eth0: 192.168.146.141 LVS-dr-slave eth0: 192.168.146.142 nginx1: eth0: ...

  7. UIView动画上

    主要参考:http://blog.csdn.net/huifeidexin_1/article/details/7597868  http://www.2cto.com/kf/201409/33566 ...

  8. bootstrap轮播图

    <!doctype html><html><head> <meta charset="utf-8"> <title>使用 ...

  9. Mybatis 的配置xml和properties放在jar包以外的一种方法

    1.问题 开发时候,将xml和properties放resources,直接可以访问到,然而打包后这两个文件也一同被打包到jar包里面,如果发布后想修改就会比较麻烦,所以希望将xml配置文件和prop ...

  10. C++ 小知识点 WINAPI

    int WINAPI WINMain 中,WINAPI含义 网友给出回答:在windef.h头文件中有如下定义#define WINAPI      __stdcall#define APIENTRY ...