{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Image-colored wordcloud\n\nYou can color a word-cloud by using an image-based coloring strategy\nimplemented in ImageColorGenerator. It uses the average color of the region\noccupied by the word in a source image. You can combine this with masking -\npure-white will be interpreted as 'don't occupy' by the WordCloud object when\npassed as mask.\nIf you want white as a legal color, you can just pass a different image to\n\"mask\", but make sure the image shapes line up.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from os import path\nfrom PIL import Image\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\n\n# get data directory (using getcwd() is needed to support running example in generated IPython notebook)\nd = path.dirname(__file__) if \"__file__\" in locals() else os.getcwd()\n\n# Read the whole text.\ntext = open(path.join(d, 'alice.txt')).read()\n\n# read the mask / color image taken from\n# http://jirkavinse.deviantart.com/art/quot-Real-Life-quot-Alice-282261010\nalice_coloring = np.array(Image.open(path.join(d, \"alice_color.png\")))\nstopwords = set(STOPWORDS)\nstopwords.add(\"said\")\n\nwc = WordCloud(background_color=\"white\", max_words=2000, mask=alice_coloring,\n               stopwords=stopwords, max_font_size=40, random_state=42)\n# generate word cloud\nwc.generate(text)\n\n# create coloring from image\nimage_colors = ImageColorGenerator(alice_coloring)\n\n# show\nfig, axes = plt.subplots(1, 3)\naxes[0].imshow(wc, interpolation=\"bilinear\")\n# recolor wordcloud and show\n# we could also give color_func=image_colors directly in the constructor\naxes[1].imshow(wc.recolor(color_func=image_colors), interpolation=\"bilinear\")\naxes[2].imshow(alice_coloring, cmap=plt.cm.gray, interpolation=\"bilinear\")\nfor ax in axes:\n    ax.set_axis_off()\nplt.show()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.13.5"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}