Python标签云拟合图片

借助Python,可以轻松地用标签云拼出一副图片,就像上图这样。让我们一起看看具体的步骤吧。

环境

请确保Python3和pip3(即python3 -m pip)都可以正常使用。需要使用pip安装的模块有:

  • matplotlib
  • numpy
  • pillow
  • wordcloud

其中wordcloud模块有些特殊,博主尝试执行pip3 install wordcloud,结果却遇到了错误信息。如果在你看到这篇文章时,该项目的维护者仍然没有解决该问题,请执行以下安装方式:

1
2
3
4
git clone https://github.com/amueller/word_cloud.git
cd word_cloud
pip3 install -r requirements.txt
python3 setup.py install

这样就完成安装了。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env python3

import numpy as np
from PIL import Image
from wordcloud import WordCloud, ImageColorGenerator
import matplotlib.pyplot as plt

pic = np.array(Image.open("path/to/your/image.png"))
jsondict = {
"Unix": 9,
"Linus Torvalds": 8,
"Richard Stallman": 8,
"open source": 3,
"Gentoo": 3,
"Archlinux": 3,
"Void Linux": 3,
"Guix": 3,
"free software": 8,
"RadHat": 3,
"php": 3,
"SUSE": 3,
"Ruby": 3,
"Python": 3,
"Go": 3,
"Mandriva": 3,
"root": 5,
"android": 4,
"Lisp": 6,
"C": 3,
"Haskell": 3,
"XMonad": 3,
"javascript": 6,
"clojure": 3,
"bash": 3,
"vim": 4,
"emacs": 4,
"vis": 4,
"ls": 3,
"cd": 3,
"grep": 3,
"sed": 3,
"awk": 3,
"pascal": 3,
"GNU": 9,
"irc": 3,
"inkscape": 3,
"github": 5,
"gitlab": 4,
"FOSDEM": 5,
"GPL": 4,
"Free as in Freedom": 5,
"FOSS": 4,
"Mozilla": 3,
"Busybox": 3,
"qemu": 3,
"gnome": 3,
"android": 3,
"Fedora": 3,
"R": 3,
"xelatex": 3,
"mupdf": 3,
"chromium": 3,
"riot": 3,
"pidgin": 3,
"vlc": 3,
"deadbeef": 3,
"xarchiver": 3,
"calibre": 3,
"s6": 3,
"json": 3,
"chez scheme": 3,
"GIMP": 3,
"gcc": 3,
"debian": 3,
"printf(\"Linux\")": 3,
"echo Linux": 3,
"(println \"Linux\")": 3,
"console.log \"Linux\"": 3,
"(format t \"Linux\")": 3,
"writeln(\"Linux\")": 3,
"PRINT \"Linux\"": 3,
"(insert \"Linux\")": 3,
"fmt.Println(\"Linux\")": 3,
"main = putStrLn \"Linux\"": 3,
"(display \"Linux\")": 3,
"System.out.println(\"Linux\");": 3,
"document.write(\"Linux\")": 3,
"type [Linux]": 3,
"disp('Linux')": 3,
"<?php\necho \"Linux\"\n?>": 3,
"Ubuntu": 3
}
image_colors = ImageColorGenerator(pic, [255, 255, 255])
wc = WordCloud(background_color = "white", mask = pic)
wc.generate_from_frequencies(jsondict)

plt.imshow(wc.recolor(color_func = image_colors), interpolation = "bilinear")
plt.axis("off")
plt.show()

path/to/your/image.png换为你要制作的图片,例如下面这张:

当然也可以替换为自己的图片,支持多种格式,但为了保证效果,非主体部分应填充白色。
jsondict是标签云中文字的内容和权重(大小),自行修改即可。
保存后使用python3执行以上代码,即可得到拟合出的图片。

🍭支持一根棒棒糖!
0%