Skip to content

[Python] Add a background to the word cloud generated using the wordcloud package

Recently, I studied a word cloud generation tool for a while, and of course I used the famous wordcloud package in python. I currently have a function that I want to do is to customize the background of the picture, but I only found the use of a picture mask to reshape the word cloud.

May be that this add background function is too simple, so Instead, no one discussed it.

The intuitive method is to make the background of the word cloud transparent.


Customize the Background Image

To use python pillow package to do it.

Suppose I have the following picture:


Then I used the following code to process:

# 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:


In this way, it succeeded, and this is the effect I want to achieve. Basically, I think the most important thing is just the following lines:

# 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)



Here I convert the word cloud generated by wordcloud into a numpy array, and then read it into a picture.

Then I read in the background image, and then resize it to the same size as the image generated by the word cloud.

Finally, use Image.alpha_composite() directly to merge them together. It's actually very simple.


References


Read More

Leave a ReplyCancel reply

Exit mobile version