|
| 1 | +#!/usr/bin/env python |
| 2 | +""" |
| 3 | +Using custom colors |
| 4 | +=================== |
| 5 | +
|
| 6 | +Using the recolor method and custom coloring functions. |
| 7 | +""" |
| 8 | + |
| 9 | +import numpy as np |
| 10 | +from PIL import Image |
| 11 | +from os import path |
| 12 | +import matplotlib.pyplot as plt |
| 13 | +import random |
| 14 | + |
| 15 | +from wordcloud import WordCloud, STOPWORDS |
| 16 | + |
| 17 | + |
| 18 | +def grey_color_func(word, font_size, position, orientation, random_state=None, |
| 19 | + **kwargs): |
| 20 | + return "hsl(0, 0%%, %d%%)" % random.randint(60, 100) |
| 21 | + |
| 22 | +d = path.dirname(__file__) |
| 23 | + |
| 24 | +# read the mask image |
| 25 | +# taken from |
| 26 | +# http://www.stencilry.org/stencils/movies/star%20wars/storm-trooper.gif |
| 27 | +mask = np.array(Image.open(path.join(d, "stormtrooper_mask.png"))) |
| 28 | + |
| 29 | +# movie script of "a new hope" |
| 30 | +# http://www.imsdb.com/scripts/Star-Wars-A-New-Hope.html |
| 31 | +# May the lawyers deem this fair use. |
| 32 | +text = open(path.join(d, 'a_new_hope.txt')).read() |
| 33 | + |
| 34 | +# preprocessing the text a little bit |
| 35 | +text = text.replace("HAN", "Han") |
| 36 | +text = text.replace("LUKE'S", "Luke") |
| 37 | + |
| 38 | +# adding movie script specific stopwords |
| 39 | +stopwords = set(STOPWORDS) |
| 40 | +stopwords.add("int") |
| 41 | +stopwords.add("ext") |
| 42 | + |
| 43 | +wc = WordCloud(max_words=1000, mask=mask, stopwords=stopwords, margin=10, |
| 44 | + random_state=1).generate(text) |
| 45 | +# store default colored image |
| 46 | +default_colors = wc.to_array() |
| 47 | +plt.title("Custom colors") |
| 48 | +plt.imshow(wc.recolor(color_func=grey_color_func, random_state=3), |
| 49 | + interpolation="bilinear") |
| 50 | +wc.to_file("a_new_hope.png") |
| 51 | +plt.axis("off") |
| 52 | +plt.figure() |
| 53 | +plt.title("Default colors") |
| 54 | +plt.imshow(default_colors, interpolation="bilinear") |
| 55 | +plt.axis("off") |
| 56 | +plt.show() |
0 commit comments