大致思路:Python扩展库wordcloud可以用来制作词云,而pillow库提供了图像处理功能,代码结合二者创建了词云头像,其中把给定的图像作为参考,只保留词云中与图像前景对应位置的像素,起到裁剪作用。
import random import string import wordcloud from PIL import Image
def show(s): # 创建wordcloud对象 wc = wordcloud.WordCloud( r'C:\windows\fonts\simfang.ttf', width=500, height=400, background_color='white', font_step=3, random_state=False, prefer_horizontal=0.9) # 创建并显示词云 t = wc.generate(s) t.to_image().save('t.png')
# 如果空间足够,就全部显示 # 如果词太多,就按频率显示,频率越高的词越大 show('hello world 董付国 董付国 董付国 董付国 abc fgh yhnbgfd 董付国 董付国 董付国 董付国 Python great Python Python')
上面代码某次运行生成的图片为:
def create(imgFile, s): im = Image.open(imgFile) w, h = im.size # 创建wordcloud对象 wc = wordcloud.WordCloud( r'C:\windows\fonts\simfang.ttf', width=w, height=h, background_color='white', font_step=3, random_state=False, prefer_horizontal=0.9) # 创建并显示词云 t = wc.generate(s) t = t.to_image() for w1 in range(w): for h1 in range(h): if im.getpixel((w1,h1))[:3] == (255,255,255): t.putpixel((w1,h1), (255,255,255))
t.save('result.png')
chs = string.ascii_letters + string.digits + string.punctuation
s = [''.join((random.choice(chs) for i in range(8))) for j in range(650)] s = ' '.join(s) create('test1.png', s)
上面代码测试图像和生成的词云图像分别为