使用word cloud提高分辨率并移除空bord

2024-06-10 08:07:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在对一些txt文件使用word cloud。如果我想1)提高分辨率,2)删除空边框,如何更改this example

#!/usr/bin/env python2
"""
Minimal Example
===============
Generating a square wordcloud from the US constitution using default arguments.
"""

from os import path
import matplotlib.pyplot as plt
from wordcloud import WordCloud

d = path.dirname(__file__)

# Read the whole text.
text = open(path.join(d, 'constitution.txt')).read()
wordcloud = WordCloud().generate(text)
# Open a plot of the generated image.
plt.imshow(wordcloud)
plt.axis("off")
plt.show()

Tags: 文件thepathtextfromimporttxtcloud
3条回答

如果你想用一个图像作为遮罩,一定要用大图像来获得更好的图像质量。。我花了好几个小时才弄明白。

下面是我使用的一个代码片段示例

mask = np.array(Image.open('path_to_your_image'))
image_colors = ImageColorGenerator(mask)
wordcloud = WordCloud(width=1600, height=800, background_color="rgba(255, 255, 255, 0)", mask=mask
                     ,color_func = image_colors).generate_from_frequencies(x)

# Display the generated image:
plt.figure( figsize=(20,10) )
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")

您不能在plt.show()中增加图像的分辨率,因为这是由屏幕决定的,但是您可以增加大小。这使得它可以缩放、缩放等而不会模糊。要执行此操作,请将维度传递到WordCloud,例如

wordcloud = WordCloud(width=800, height=400).generate(text)

但是,这只决定了由WordCloud创建的图像的大小。当您使用matplotlib显示时,它将缩放到绘图画布的大小,即(默认情况下)大约800x600,您将再次失去质量。要解决这个问题,您需要在调用imshow之前指定图形的大小,例如

plt.figure( figsize=(20,10) )
plt.imshow(wordcloud)

通过这样做,我可以成功地创建一个2000x1000高分辨率字云。

对于您的第二个问题(删除边框),首先我们可以将边框设置为黑色,这样就不那么明显了,例如

plt.figure( figsize=(20,10), facecolor='k' )

也可以使用tight_layout缩小边框的大小,例如

plt.tight_layout(pad=0)

最终代码:

# Read the whole text.
text = open(path.join(d, 'constitution.txt')).read()
wordcloud = WordCloud(width=1600, height=800).generate(text)
# Open a plot of the generated image.

plt.figure( figsize=(20,10), facecolor='k')
plt.imshow(wordcloud)
plt.axis("off")
plt.tight_layout(pad=0)
plt.show()

将最后两行替换为以下内容,可以得到如下所示的最终输出:

plt.savefig('wordcloud.png', facecolor='k', bbox_inches='tight')

final Constitution wordcloud

它非常简单,plt.tight_layout(pad=0)完成任务,减少背景空间,去掉多余的填充。

相关问题 更多 >