Python实现根据图片进行着色的词云
生活随笔
收集整理的這篇文章主要介紹了
Python实现根据图片进行着色的词云
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
效果
?
?
?
實(shí)現(xiàn)
通過(guò)使用ImageColorGenerator中實(shí)現(xiàn)的基于圖像的著色策略,可以對(duì)單詞云進(jìn)行著色。
它使用源圖像中單詞所占據(jù)的區(qū)域的平均顏色。
您可以結(jié)合使用掩碼——純白色在作為掩碼傳遞時(shí)被WordCloud對(duì)象解釋為“不要占用”。如果你想要白色作為合法的顏色,你可以只傳遞一個(gè)不同的圖像到“蒙版”,但要確保圖像形狀排列。
打開IDLE,新建文件image-colored.py
在同目錄下新建aobama.txt,用來(lái)作為詞云的數(shù)據(jù)源。
bg.jpn是作為背景以及著色圖取色的照片。
源碼:
from os import path from PIL import Image import numpy as np import matplotlib.pyplot as plt import osfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator# get data directory (using getcwd() is needed to support running example in generated IPython notebook) d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()# Read the whole text. text = open(path.join(d, 'aobama.txt')).read()# read the mask / color image taken from # http://jirkavinse.deviantart.com/art/quot-Real-Life-quot-Alice-282261010 alice_coloring = np.array(Image.open(path.join(d, "bg.jpg"))) stopwords = set(STOPWORDS) stopwords.add("said")wc = WordCloud(background_color="white", max_words=2000, mask=alice_coloring,stopwords=stopwords, max_font_size=40, random_state=42) # generate word cloud wc.generate(text)# create coloring from image image_colors = ImageColorGenerator(alice_coloring)# show fig, axes = plt.subplots(1, 3) axes[0].imshow(wc, interpolation="bilinear") # recolor wordcloud and show # we could also give color_func=image_colors directly in the constructor axes[1].imshow(wc.recolor(color_func=image_colors), interpolation="bilinear") axes[2].imshow(alice_coloring, cmap=plt.cm.gray, interpolation="bilinear") for ax in axes:ax.set_axis_off() plt.show()?
保存并運(yùn)行。
總結(jié)
以上是生活随笔為你收集整理的Python实现根据图片进行着色的词云的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Python实现生成一个单词的圆形词云
- 下一篇: 快速上手用Python搭建自己的第一个p