ML之Hierarchical clustering:利用层次聚类算法来把100张图片自动分成红绿蓝三种色调

328 篇文章 73 订阅

ML之Hierarchical clustering:利用层次聚类算法来把100张图片自动分成红绿蓝三种色调

 

 

目录

输出结果

实现代码


 

 

 

 

输出结果

 

 

实现代码

#!/usr/bin/python
# coding:utf-8
from PIL import Image, ImageDraw   
from HierarchicalClustering import hcluster   
from HierarchicalClustering import getheight
from HierarchicalClustering import getdepth
import numpy as np
import os

def drawdendrogram(clust, imlist, jpeg= 'clusters.jpg'): 
    h = getheight(clust)*20      
    w = 1200
    depth = getdepth(clust)     
    scaling = float(w - 150)/depth 
    
    img = Image.new('RGB', (w, h), (255, 255, 255)) 
    draw = ImageDraw.Draw(img)                       

    draw.line((0, h/2, 10, h/2), fill=(255, 0, 0))   
    drawnode(draw, clust, 10, int(h/2), scaling, imlist, img)  
    img.save(jpeg)    

def drawnode(draw,clust,x,y,scaling,imlist,img):     if clust.id < 0: 
        h1 = getheight(clust.left)*20
        h2 = getheight(clust.right)*20
        top = y - (h1 + h2)/2
        bottom = y + (h1 + h2)/2
        ll = clust.distance * scaling
        draw.line((x, top + h1/2, x, bottom - h2/2), fill=(255, 0, 0))

        draw.line((x, top + h1/2, x + ll, top + h1/2), fill=(255, 0, 0))

        draw.line((x, bottom - h2/2, x + ll, bottom - h2/2), fill=(255, 0, 0))

        drawnode(draw, clust.left, x + ll, top + h1/2, scaling, imlist, img)
        drawnode(draw, clust.right, x + ll, bottom - h2/2, scaling, imlist, img)
    else: 
        nodeim = Image.open(imlist[clust.id])
        nodeim.thumbnail((20, 20))   
        ns = nodeim.size
        print (x,y - ns[1]//2)
        print (x + ns[0])
        print (img.paste(nodeim, (int(x), int(y - ns[1]//2), int(x + ns[0]),int(y + ns[1] - ns[1]//2))))

imlist=[]
folderpath = r'F:\File_Python\Crawler'        
for filename in os.listdir(folderpath): 
    if os.path.splitext(filename)[1]=='.jpg':
        imlist.append(os.path.join(folderpath,filename))
n=len(imlist)  
print(n)

features =np.zeros((n,3))  
for i in range(n):         
    im=np.array(Image.open(imlist[i])) 
    R = np.mean(im[:,:,0].flatten())    
    G = np.mean(im[:,:,1].flatten())
    B = np.mean(im[:,:,2].flatten())
    features[i]=np.array([R,G,B])
    
tree = hcluster(features)   
drawdendrogram(tree, imlist, jpeg=r'C:\Users\99386\Desktop\result.jpg')  #

 

 


相关文章
ML之H-clustering:自定义HierarchicalClustering层次聚类算法
ML之H-clustering:利用层次聚类算法来把100张图片自动分成红绿蓝三种色调
 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一个处女座的程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值