在做词云图的时候,因为需要指定形状的词云图,所以想到用ppt绘制形状,将透明背景的形状另存为png图片保存到本地。 保存的图片如下:
再调用wordcloud包绘制词云图,设置词云背景为前面保存的png图片。
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
from imageio import imread
text = open("text.txt", encoding='utf-8').read()
text = text.replace('\n', "").replace("\u3000", "")
text_cut = jieba.lcut(text)
text_cut = ' '.join(text_cut)
stop_words = open("stopwords.txt", encoding="utf8").read().split("\n")
background = Image.open("cloud.png").convert('RGB')
graph = np.array(background)
word_cloud = WordCloud(scale=4,
font_path="msyh.ttc",
relative_scaling=0.1,
background_color="white",
mask=graph,
stopwords=set(stop_words)
)
word_cloud.generate(text_cut)
plt.subplots(figsize=(12, 8))
plt.imshow(word_cloud)
plt.axis("off")
plt.show()
结果如下,不知道为什么,生成的图云还是矩形形状。 了解到ppt绘制的形状图用python读取后原本的透明背景变成了白色背景。🆗 那就用python把白色背景变透明吧。
把png的白色背景变透明
import PIL.Image as Image
img = Image.open('cloud.png').convert('RGBA')
W, L = img.size
white_pixel = (0, 0, 0, 0)
for h in range(W):
for i in range(L):
if img.getpixel((h, i)) == white_pixel:
img.putpixel((h, i), (255, 255, 255, 0))
img.save('cloud_new.png')
修改后的词云背景图片cloud_new.png如下:
用修改后的词云背景cloud_new.png重新跑一遍词云代码,生成的词云结果如下:
参考:https://cloud.tencent.com/developer/article/1847968
|