# -*- 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. Struts框架核心工作流程与原理

    1.Struts2架构图  这是Struts2官方站点提供的Struts 2 的整体结构.  执行流程图 2.Struts2部分类介绍  这部分从Struts2参考文档中翻译就可以了. ActionM ...

  2. .NET Framework 源码查看与调试

    1. 直接下载.NET Framework源代码(下载地址),然后用Visual Studio 13 打开查看.2. 在线查看,网址:http://referencesource.microsoft. ...

  3. 堆与堆排序/Heap&Heap sort

    最近在自学算法导论,看到堆排序这一章,来做一下笔记.堆排序是一种时间复杂度为O(lgn)的原址排序算法.它使用了一种叫做堆的数据结构.堆排序具有空间原址性,即指任何时候都需要常数个额外的元素空间存储临 ...

  4. java开发细节问题,spring的单例模式,多线程同步问题

    1.对象的赋值,new一个对象,然后在传递给函数赋值,往往这对对象赋值就可以使用了 2.对于 spring开发的细节问题 Spring框架里的bean,或者说组件,获取实例的时候都是默认的单例模式,这 ...

  5. vim 常用命令(一)特殊删除

    dd 可以删除光标当前行: ndd  n代表行数,3dd,删除从当前光标往下3行: di 删除在指定符号内的内容,如 空号,引号内: dt 删除当前光标到指定符号的内容

  6. Maven3路程(一)环境搭建

    好长时间不用Java,今天看了下,Maven集成成主流了,在技术水平与日俱进的同时,感叹下IT行业必须有活到老学到老的精神. 先说下环境: Maven:Maven 3.0.5 解压后路径:F:\Mav ...

  7. 简单Demo 使用Code Fisrt步骤

    使用Code Fisrt步骤 1.开启VS,创建控制台项目:CodeFirstDemo1 2.利用NuGet引进 Entity Framework类库          图住:右击项目名称,在弹出的选 ...

  8. 【IT笔试面试题整理】反转链表

    [试题描述]定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点 [参考代码] 方法一: public static Link reverseLinkList(Link head) ...

  9. 合并两个数组并去重(ES5和ES6两种方式实现)

    合并两个数组并去重(ES5和ES6两种方式实现) ES6实现方式 let arr1 = [1, 1, 2, 3, 6, 9, 5, 5, 4] let arr2 = [1, 2, 5, 4, 9, 7 ...

  10. 使用vertical-align实现垂直对齐

    关于垂直对齐,之前研究过好几次了,但感觉每次都没研究透彻,做了几个效果,就觉得自己掌握了,实在是自欺欺人.真乃搞技术的大忌. 这两天又下定决心重新开始研究vertical-allign这个高深莫测的属 ...