# -*- 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. 从学CodeSmith谈程序员学习方法

    一直觉得CodeSmith是个好东西,最近正好有点时间来研究下,其实以前也想学习怎么用,在博客园搜一下有很多介绍CodeSmith的文章,我就收藏过一个写得很详细的http://terrylee.cn ...

  2. java学习-排序及加密签名时数据排序方式

    排序有两种 1. 类实现comparable接口调用List.sort(null)或Collections.sort(List<T>)方法进行排序 jdk内置的基本类型包装类等都实现了Co ...

  3. 【详解】ThreadPoolExecutor源码阅读(二)

    系列目录 [详解]ThreadPoolExecutor源码阅读(一) [详解]ThreadPoolExecutor源码阅读(二) [详解]ThreadPoolExecutor源码阅读(三) AQS在W ...

  4. Selenium3自动化问题一:selenium3在火狐浏览器执行driver.quit()报错2052解决方案

    一:问题说明 最近用到selenium3在火狐浏览器中执行自动化脚本,每次执行到driver.quit()方法总是报错,报错日志如下: 二:解决方案 搜了一圈网上的资料,都说是火狐的问题,于是去到se ...

  5. 【一个小功能】从js判断ie版本,浅谈navigator对象的appName属性

    判断IE版本主要的是获取两个属性,a.当前浏览器名称,b.当前浏览器版本,为此不得不了解navigator对象. 先贴代码 window.onload = function() { var brows ...

  6. java面向对象基础(三):对象转型和多态

    */ .hljs { display: block; overflow-x: auto; padding: 0.5em; color: #333; background: #f8f8f8; } .hl ...

  7. 念念不忘,ASP.NET MVC显示WebForm网页或UserControl控件

    学习与使用ASP.NET MVC这样久,还是对asp.net念念不忘.能否在asp.net mvc去显示aspx或是user control呢?这个灵感(算不上灵感,只能算是想法)是来自前些天有写过一 ...

  8. PetaPoco源代码学习--0.目录贴

    2017年3季度后,以人力外包的形式派驻到甲方单位进行项目救急时,接触到了甲方单位的ASP.NET MVC项目的ORM框架,它以PetaPoco(2012年的老版本)进行改造升级的,当初就想学习一下这 ...

  9. 一:MyBatis知识整理(1)

    一:MyBatis的架构 1.mybatis配置SqlMapConfig.xml,此文件作为mybatis的全局配置文件,配置了mybatis的运行环境等信息. mapper.xml文件即sql映射文 ...

  10. Python发送短信提醒

    Python发送短信可借助腾讯云平台提供的短信服务 发送短信需要的及格参数: 1.SDK_AppID和SDK_Key 2.签名: 3.模板ID 下面贴出源码DEMO: from qcloudsms_p ...