# 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')  #

4818 0
CV：基于face库利用cv2调用摄像头(或视频)根据人脸图片实现找人(先指定要识别已知人脸的文件夹转为numpy_array+输入新图片遍历已有numpy_array)
CV：基于face库利用cv2调用摄像头(或视频)根据人脸图片实现找人(先指定要识别已知人脸的文件夹转为numpy_array+输入新图片遍历已有numpy_array)
14 0
listview 点击条目 自动置顶或者自动置底部

561 0

1008 0
Matlab实现K-Means聚类算法

1281 0
ML之SVM：利用SVM算法对手写数字图片识别数据集(PCA降维处理)进行预测并评估模型(两种算法)性能
ML之SVM：利用SVM算法对手写数字图片识别数据集(PCA降维处理)进行预测并评估模型(两种算法)性能
18 0
+关注

1701

0

《SaaS模式云原生数据仓库应用场景实践》

《看见新力量：二》电子书