Skip to content

Instantly share code, notes, and snippets.

@keithstellyes
Created February 4, 2017 06:25
Show Gist options
  • Save keithstellyes/0044608d50d8317b5530e7274a92effa to your computer and use it in GitHub Desktop.
Save keithstellyes/0044608d50d8317b5530e7274a92effa to your computer and use it in GitHub Desktop.
Python word cloud example that takes an image, a source string, and builds a word cloud to match the image.
from wordcloud import WordCloud, ImageColorGenerator
from PIL import Image
import numpy as np
s = input("Source text:")
p = input("Image file:")
outfile = input("Out file?")
s = open(s, 'r').read()
coloring = np.array(Image.open(p))
image_colors=ImageColorGenerator(coloring)
# These settings need to be messed with or it won't really work :^)
# see the colored.py example in the word_cloud repo
# As in, needing to set color, max words, etc.
# It may be worth tweaking for better results
# See: https://github.com/amueller/word_cloud/blob/master/examples/colored.py
wc = WordCloud(background_color='white', max_words=2000, max_font_size=40,
mask=coloring)
wc.generate(s)
wc.recolor(color_func=image_colors)
wc.to_file(outfile)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment