Python实现根据图片进行着色的词云

效果

Python实现根据图片进行着色的词云Python实现根据图片进行着色的词云

 

 

 

Python实现根据图片进行着色的词云

Python实现根据图片进行着色的词云

实现

通过使用ImageColorGenerator中实现的基于图像的着色策略,可以对单词云进行着色。

它使用源图像中单词所占据的区域的平均颜色。

您可以结合使用掩码——纯白色在作为掩码传递时被WordCloud对象解释为“不要占用”。如果你想要白色作为合法的颜色,你可以只传递一个不同的图像到“蒙版”,但要确保图像形状排列。

打开IDLE,新建文件image-colored.py

在同目录下新建aobama.txt,用来作为词云的数据源。

bg.jpn是作为背景以及着色图取色的照片。

源码:

from os import path
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import os

from 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()

 

保存并运行。