{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Image-colored wordcloud with boundary map\nA slightly more elaborate version of an image-colored wordcloud\nthat also takes edges in the image into account.\nRecreating an image similar to the parrot example.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import os\nfrom PIL import Image\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.ndimage import gaussian_gradient_magnitude\n\nfrom wordcloud import WordCloud, ImageColorGenerator\n\n# get data directory (using getcwd() is needed to support running example in generated IPython notebook)\nd = os.path.dirname(__file__) if \"__file__\" in locals() else os.getcwd()\n\n# load wikipedia text on rainbow\ntext = open(os.path.join(d, 'wiki_rainbow.txt'), encoding=\"utf-8\").read()\n\n# load image. This has been modified in gimp to be brighter and have more saturation.\nparrot_color = np.array(Image.open(os.path.join(d, \"parrot-by-jose-mari-gimenez2.jpg\")))\n# subsample by factor of 3. Very lossy but for a wordcloud we don't really care.\nparrot_color = parrot_color[::3, ::3]\n\n# create mask  white is \"masked out\"\nparrot_mask = parrot_color.copy()\nparrot_mask[parrot_mask.sum(axis=2) == 0] = 255\n\n# some finesse: we enforce boundaries between colors so they get less washed out.\n# For that we do some edge detection in the image\nedges = np.mean([gaussian_gradient_magnitude(parrot_color[:, :, i] / 255., 2) for i in range(3)], axis=0)\nparrot_mask[edges > .08] = 255\n\n# create wordcloud. A bit sluggish, you can subsample more strongly for quicker rendering\n# relative_scaling=0 means the frequencies in the data are reflected less\n# acurately but it makes a better picture\nwc = WordCloud(max_words=2000, mask=parrot_mask, max_font_size=40, random_state=42, relative_scaling=0)\n\n# generate word cloud\nwc.generate(text)\nplt.imshow(wc)\n\n# create coloring from image\nimage_colors = ImageColorGenerator(parrot_color)\nwc.recolor(color_func=image_colors)\nplt.figure(figsize=(10, 10))\nplt.imshow(wc, interpolation=\"bilinear\")\nwc.to_file(\"parrot_new.png\")\n\nplt.figure(figsize=(10, 10))\nplt.title(\"Original Image\")\nplt.imshow(parrot_color)\n\nplt.figure(figsize=(10, 10))\nplt.title(\"Edge map\")\nplt.imshow(edges)\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
}