Skip to content

[Python] wordcloud 自定義背景圖片

我最近研究了一會兒的文字雲產生工具,使用的當然是 Python 上鼎鼎有名的 wordcloud。目前我有個想做的功能是自定義圖片的背景,不過上網一查目前只有找到使用圖片遮罩置換圖片形狀 …… 我直覺可能是這個功能太簡單、而且太單純了,所以反而沒什麼人討論。

畢竟只要設定為透明背景即可替換了。或許原本的套件就有這個功能?不過我只是匆匆瀏覽過,並沒有找到。

那麼,我就來紀錄一下怎麼做出這個功能。


自定義圖片背景

基本觀念便是,將 wordcloud 產生的圖片生成為透明背景、然後使用 Python 中的 PIL 模組將其與背景圖片 composite 在一起即可。

假設我有一張以下這樣的圖片:

然後我使用以下程式碼處理:

# coding: utf-8
import matplotlib.pyplot as plt
from PIL import Image
from wordcloud import WordCloud


# Load
text = open('data/wiki_rainbow.txt', 'r', encoding='utf-8').read()


# WordCloud
wc = WordCloud(mode='RGBA',
               background_color='rgba(255, 255, 255, 0)')
wc.generate(text)


# Image process
image = Image.fromarray(wc.to_array())
background = Image.open('pic/bg01.png')
background = background.resize(image.size)
new_image = Image.alpha_composite(background, image)


# Plot
plt.figure()
plt.axis('off')
plt.imshow(new_image)
plt.show()


# Save
plt.figure()
plt.axis('off')
fig = plt.imshow(new_image, interpolation='nearest')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.savefig('test.png',
            bbox_inches='tight',
            pad_inches=0,
            format='png',
            dpi=300)



Output:

這張圖片的 alt 屬性值為空,它的檔案名稱為 image-45.png

這樣一來就成功了,這就是我想要達成的效果。基本上,我覺得最重要的就只是下面幾行:

# Image process
image = Image.fromarray(wc.to_array())
background = Image.open('pic/bg01.png')
background = background.resize(image.size)
new_image = Image.alpha_composite(background, image)



這裡我將 wordcloud 產生的文字雲轉成 numpy array,然後讀取成圖片。

然後我將背景圖片讀進來,然後 Resize 成跟文字雲產生的圖片一樣大小。

最後直接使用 Image.alpha_composite() 合併在一起。其實非常單純。


References


Read More

Leave a Reply