# -*- 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. Spring Boot 基础概述与相关约定配置

    今天打算整理一下 Spring Boot 的基础篇,这系列的文章是我业余时间来写的,起源于之前对微服务比较感兴趣,微服务的范畴比较广包括服务治理.负载均衡.断路器.配置中心.API网关等,还需要结合 ...

  2. SQL 日期相减(间隔)datediff函数

    select datediff(year, 开始日期,结束日期); --两日期间隔年 select datediff(quarter, 开始日期,结束日期); --两日期间隔季 select date ...

  3. JavaScript -- Window-Blur

    -----030-Window-Blur.html----- <!DOCTYPE html> <html> <head> <meta http-equiv=& ...

  4. 记一次使用mybatis进行like 模糊查询遇到的问题

    "bdate like '#{date}%' and ..." 最开始这样写的· 将传入的参数和%用单引号包起来,但是这会报错 java.sql.SQLException: Par ...

  5. visual studio code 个人设置

    { "vim.disableAnnoyingNeovimMessage": true, "php.validate.executablePath": " ...

  6. Windows x86 下的 静态代码混淆

    0x00  前言 静态反汇编之王,毫无疑问就是Ida pro,大大降低了反汇编工作的门槛,尤其是出色的“F5插件”Hex-Rays可以将汇编代码还原成类似于C语言的伪代码,大大提高了可读性.但个人觉得 ...

  7. C++ STL 学习

    /* algorithm-算法 */ .copy() //此函数用在vector中只做拷贝使用,它不能让vector有自动扩充作用.如果vector的容量小于它拷贝的数据量将会报错. /* itera ...

  8. 启用sa账号

    第一部分: 如果在安装的时候选中的是Window身份验证,后来需要SQLServer身份验证登录,那么 一.先用window账号登录数据库 二.启用window身份验证和sql sever身份验证方式 ...

  9. rsync --include-from --exclude-from的理解

    rsync --include-from --exclude-from的理解: 1.同时添加--include-from --exclude-from时.后者是对前者的结果进行排除 如:“--incl ...

  10. 配置Windows 防火墙,允许SQL Server的远程连接

    在运行SQL Server的服务器上,我们要找到哪些是SQL Server正在侦听的端口,并将其添加到Windows防火墙的入站例外. 首先,我们需要添加 SQL Server 服务侦听 Window ...