栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

第八章:Scipy-色彩聚类提取

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

第八章:Scipy-色彩聚类提取

目录

一.聚类示例(Jupyter)

二、聚类色彩提取实例

1.首先选定图片进行色彩提取,并将色彩出现频率进行排序,输出特定序列的颜色。

 2.用PIL生成小尺寸的图片,在小图片上聚类

3.取出图像的色彩和频次,代码如下:

4.对色彩聚类,代码如下: 

三.色彩聚类→网页Flask中

(一)定义网页样式

(二)聚类程序代码实现


安装:pip install scipy

一.聚类示例(Jupyter)

选取一组数据,对其进行聚类分析。代码如下:

import numpy as np
from scipy.cluster.vq import vq, kmeans, whiten
import matplotlib.pyplot as plt
 
fe = np.array([[1.9,2.0],
                     [1.7,2.5],
                     [1.6,3.1],
                     [0.1,0.1],
                     [0.8,0.3],
                     [0.4,0.3],
                     [0.22,0.1],
                     [0.4, 0.3],
                     [0.4,0.5],
                     [1.8,1.9]])
 
book = np.array((fe[0], fe[1]))
print(type(book))
print("book: n",book)
 
codebook, distortion = kmeans(fe, book)
# 可以写kmeans(wf,2), 2表示两个质心,同时启用iter参数
print("codebook:", codebook)
print("distortion: ", distortion)
 
plt.scatter(fe[:,0], fe[:,1], c='g')
plt.scatter(codebook[:, 0], codebook[:, 1], c='r')
plt.show()
#运行结果:红色的为聚类中心

输出结果:

二、聚类色彩提取实例

1.首先选定图片进行色彩提取,并将色彩出现频率进行排序,输出特定序列的颜色。
from PIL import Image, ImageDraw, ImageFont
#引入第三方库
 
def get_dominant_colors(infile):
    #定义获取图片颜色的函数
    image = Image.open(infile)
    #读取图片
    
    small_image = image.resize((80, 80))
    #缩小图片,减少计算量
    
    result = small_image.convert("P", palette=Image.ADAPTIVE, colors=5)  
    #获取图片中5个主要的颜色
    
    palette = result.getpalette()
    color_counts = sorted(result.getcolors(), reverse=True)
    colors = list()
    #对颜色进行排序
 
    for i in range(5):
        palette_index = color_counts[i][1]
        dominant_color = palette[palette_index * 3 : palette_index * 3 + 3]
        colors.append(tuple(dominant_color))
        #定义颜色数据输出的格式
 
    return colors
 
image_path = "/Users/air/Desktop/WechatIMG1.jpeg"
color = get_dominant_colors(image_path)
#输入具体的待处理图片
print(color)

输出结果如下:

 

 2.用PIL生成小尺寸的图片,在小图片上聚类

(用resize或者thumbnail(缩略图))

#用PIL生成小尺寸的图片,在小图片上聚类
#用resize或者thumbnail(缩略图)
 
import os
from PIL import Image
import matplotlib.pyplot as plt

im = np.array(Image.open('/Users/air/Desktop/WechatIMG1.jpeg'))
 
#用缩略图聚类
def colorz(filename,n=3):
    img=Image.open(filename)
    #print(dir(img))
    img=img.resize((1024,1024))
    img=img.rotate(-90)
    print(img.size)
    plt.axis('off')
    plt.imshow(img)
    plt.show()
    
    img.thumbnail((200,200))#缩略图
    w,h=img.size
    print(w,h)
    plt.axis('off')
    plt.imshow(img)
    plt.show()
colorz('/Users/air/Desktop/WechatIMG1.jpeg',3)

输出结果如下:

3.取出图像的色彩和频次,代码如下:
#取出图像的色彩和频次
 
import os
from PIL import Image
import matplotlib.pyplot as plt

im = np.array(Image.open('/Users/air/Desktop/WechatIMG1.jpeg'))
 
#用缩略图聚类
def colorz(filename,n=3):
    img=Image.open(filename)
    img=img.rotate(-90)
    img.thumbnail((200,200))
    w,h=img.size
    print(w,h) 
    print('w*h=',w*h)
    plt.axis('off')
    plt.imshow(img)
    plt.show()
    points=[]#列表
    for count,color in img.getcolors(w*h):
        points.append(color)
    return points
colorz('/Users/air/Desktop/WechatIMG1.jpeg',3)

 输出结果为:

4.对色彩聚类,代码如下: 
import numpy as np
from scipy.cluster.vq import vq, kmeans, whiten
import matplotlib.pyplot as plt
 
 
points=colorz('/Users/air/Desktop/WechatIMG1.jpeg',3)
print(points[0:10])
 
fe = np.array(points,dtype=float)   #聚类需要是Float或者Double
print(fe[0:10])
book =np.array((fe[100],fe[1],fe[8],fe[8]))   #聚类中心,初始值
print(type(book))
print("book: n",book)
 
#codebook, distortion = kmeans(fe,book)
codebook, distortion = kmeans(fe,7)   #7是聚类中心个数,distortion控制方差大小
# 可以写kmeans(wf,2), 2表示两个质心,同时启用iter参数
 
print("codebook:", codebook)   #聚类中心
centers=np.array(codebook,dtype=int)  #变为色彩,还得转为整数
print(centers)
print("distortion: ", distortion)
 
fe=np.array(points)
plt.scatter(fe[:,0], fe[:,2], c='b')
plt.scatter(codebook[:, 0], codebook[:,2], c='r')   #聚类中心
plt.show()
#有七个聚类中心

输出结果为:

三.色彩聚类→网页Flask中

(一)定义网页样式


帧数: {{framecount}}
{{imgcolors}}
{% for c in imgcolors %} 金城武 {% endfor %}

(二)聚类程序代码实现
import numpy as np
from PIL import Image
from scipy.cluster.vq import vq, kmeans, whiten
from flask import Flask,render_template,request
import imageColor
#导入第三方库
 
app=Flask(__name__)
 
def colorz(filename,n=3):
    img=Image.open(filename)
    img=img.rotate(-90)
    img.thumbnail((200,200))
    w,h=img.size
    print(w,h)
    print('w*h=',w*h)
    points=[]
    for count,color in img.getcolors(w*h):
        points.append(color)
    return points
#定义色彩函数
 
def kmeansColor(img,n):
    points=colorz(img,3)
    fe = np.array(points,dtype=float)
    codebook, distortion = kmeans(fe,n)
    centers=np.array(codebook,dtype=int)
    return centers
#定义聚类函数
 
@app.route('/')
def index():
    #return "Hi,Flask!"
    #genframe()
    pic='static/pic/image'
    framecount=249
    imgcolors=imageColor.kmeansColor('static/pic/image0.jpg',5)
    return render_template('index.html',pic1=pic,framecount=framecount,imgcolors=imgcolors)
#将程序结果加载到网页端
 
if "__main__"==__name__:
    app.run(port="5008")
#运行程序

输出结果:

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/581373.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号