政策资讯

Policy Information


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

来源: 重庆市软件正版化服务中心    |    时间: 2022-09-20    |    浏览量: 66564    |   

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

目录

输出结果

实现代码


输出结果

实现代码

  1. !/usr/bin/python
  2. coding:utf-8
  3. from PIL import Image, ImageDraw
  4. from HierarchicalClustering import hcluster
  5. from HierarchicalClustering import getheight
  6. from HierarchicalClustering import getdepth
  7. import numpy as np
  8. import os
  9. def drawdendrogram(clust, imlist, jpeg= 'clusters.jpg'):
  10. h = getheight(clust)*20
  11. w = 1200
  12. depth = getdepth(clust)
  13. scaling = float(w - 150)/depth
  14. img = Image.new('RGB', (w, h), (255, 255, 255))
  15. draw = ImageDraw.Draw(img)
  16. draw.line((0, h/2, 10, h/2), fill=(255, 0, 0))
  17. drawnode(draw, clust, 10, int(h/2), scaling, imlist, img)
  18. img.save(jpeg)
  19. def drawnode(draw,clust,x,y,scaling,imlist,img): if clust.id < 0:
  20. h1 = getheight(clust.left)*20
  21. h2 = getheight(clust.right)*20
  22. top = y - (h1 + h2)/2
  23. bottom = y + (h1 + h2)/2
  24. ll = clust.distance * scaling
  25. draw.line((x, top + h1/2, x, bottom - h2/2), fill=(255, 0, 0))
  26. draw.line((x, top + h1/2, x + ll, top + h1/2), fill=(255, 0, 0))
  27. draw.line((x, bottom - h2/2, x + ll, bottom - h2/2), fill=(255, 0, 0))
  28. drawnode(draw, clust.left, x + ll, top + h1/2, scaling, imlist, img)
  29. drawnode(draw, clust.right, x + ll, bottom - h2/2, scaling, imlist, img)
  30. else:
  31. nodeim = Image.open(imlist[clust.id])
  32. nodeim.thumbnail((20, 20))
  33. ns = nodeim.size
  34. print (x,y - ns[1]//2)
  35. print (x + ns[0])
  36. print (img.paste(nodeim, (int(x), int(y - ns[1]//2), int(x + ns[0]),int(y + ns[1] - ns[1]//2))))
  37. imlist=[]
  38. folderpath = r'F:\File_Python\Crawler'
  39. for filename in os.listdir(folderpath):
  40. if os.path.splitext(filename)[1]=='.jpg':
  41. imlist.append(os.path.join(folderpath,filename))
  42. n=len(imlist)
  43. print(n)
  44. features =np.zeros((n,3))
  45. for i in range(n):
  46. im=np.array(Image.open(imlist[i]))
  47. R = np.mean(im[:,:,0].flatten())
  48. G = np.mean(im[:,:,1].flatten())
  49. B = np.mean(im[:,:,2].flatten())
  50. features[i]=np.array([R,G,B])
  51. tree = hcluster(features)
  52. drawdendrogram(tree, imlist, jpeg=r'C:\Users\99386\Desktop\result.jpg')


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

评论

QQ咨询 扫一扫加入群聊,了解更多平台咨询
微信咨询 扫一扫加入群聊,了解更多平台咨询
意见反馈
立即提交
QQ咨询
微信咨询
意见反馈