{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Using custom colors\n\nUsing the recolor method and custom coloring functions.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nfrom PIL import Image\nfrom os import path\nimport matplotlib.pyplot as plt\nimport os\nimport random\n\nfrom wordcloud import WordCloud, STOPWORDS\n\n\ndef grey_color_func(word, font_size, position, orientation, random_state=None,\n                    **kwargs):\n    return \"hsl(0, 0%%, %d%%)\" % random.randint(60, 100)\n\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 mask image taken from\n# http://www.stencilry.org/stencils/movies/star%20wars/storm-trooper.gif\nmask = np.array(Image.open(path.join(d, \"stormtrooper_mask.png\")))\n\n# movie script of \"a new hope\"\n# http://www.imsdb.com/scripts/Star-Wars-A-New-Hope.html\n# May the lawyers deem this fair use.\ntext = open(path.join(d, 'a_new_hope.txt')).read()\n\n# pre-processing the text a little bit\ntext = text.replace(\"HAN\", \"Han\")\ntext = text.replace(\"LUKE'S\", \"Luke\")\n\n# adding movie script specific stopwords\nstopwords = set(STOPWORDS)\nstopwords.add(\"int\")\nstopwords.add(\"ext\")\n\nwc = WordCloud(max_words=1000, mask=mask, stopwords=stopwords, margin=10,\n               random_state=1).generate(text)\n# store default colored image\ndefault_colors = wc.to_array()\nplt.title(\"Custom colors\")\nplt.imshow(wc.recolor(color_func=grey_color_func, random_state=3),\n           interpolation=\"bilinear\")\nwc.to_file(\"a_new_hope.png\")\nplt.axis(\"off\")\nplt.figure()\nplt.title(\"Default colors\")\nplt.imshow(default_colors, interpolation=\"bilinear\")\nplt.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
}