{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n.. redirect-from:: /tutorials/introductory/images\n\n\n# Image tutorial\n\nA short tutorial on plotting images with Matplotlib.\n\n\n## Startup commands\n\nFirst, let's start IPython. It is a most excellent enhancement to the\nstandard Python prompt, and it ties in especially well with\nMatplotlib. Start IPython either directly at a shell, or with the Jupyter\nNotebook (where IPython as a running kernel).\n\nWith IPython started, we now need to connect to a GUI event loop. This\ntells IPython where (and how) to display plots. To connect to a GUI\nloop, execute the **%matplotlib** magic at your IPython prompt. There's more\ndetail on exactly what this does at [IPython's documentation on GUI\nevent loops](https://ipython.readthedocs.io/en/stable/interactive/reference.html#gui-event-loop-support).\n\nIf you're using Jupyter Notebook, the same commands are available, but\npeople commonly use a specific argument to the %matplotlib magic:\n\n.. sourcecode:: ipython\n\n In [1]: %matplotlib inline\n\nThis turns on inline plotting, where plot graphics will appear in your\nnotebook. This has important implications for interactivity. For inline plotting, commands in\ncells below the cell that outputs a plot will not affect the plot. For example,\nchanging the colormap is not possible from cells below the cell that creates a plot.\nHowever, for other backends, such as Qt, that open a separate window,\ncells below those that create the plot will change the plot - it is a\nlive object in memory.\n\nThis tutorial will use Matplotlib's implicit plotting interface, pyplot. This\ninterface maintains global state, and is very useful for quickly and easily\nexperimenting with various plot settings. The alternative is the explicit,\nwhich is more suitable for large application development. For an explanation\nof the tradeoffs between the implicit and explicit interfaces see\n`api_interfaces` and the `Quick start guide\n` to start using the explicit interface.\nFor now, let's get on with the implicit approach:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from PIL import Image\n\nimport matplotlib.pyplot as plt\nimport numpy as np" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n## Importing image data into Numpy arrays\n\nMatplotlib relies on the Pillow_ library to load image data.\n\n\nHere's the image we're going to play with:\n\n\n\nIt's a 24-bit RGB PNG image (8 bits for each of R, G, B). Depending\non where you get your data, the other kinds of image that you'll most\nlikely encounter are RGBA images, which allow for transparency, or\nsingle-channel grayscale (luminosity) images. Download [stinkbug.png](https://raw.githubusercontent.com/matplotlib/matplotlib/main/doc/_static/stinkbug.png)\nto your computer for the rest of this tutorial.\n\nWe use Pillow to open an image (with `PIL.Image.open`), and immediately\nconvert the `PIL.Image.Image` object into an 8-bit (``dtype=uint8``) numpy\narray.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "img = np.asarray(Image.open('../../doc/_static/stinkbug.png'))\nprint(repr(img))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Each inner list represents a pixel. Here, with an RGB image, there\nare 3 values. Since it's a black and white image, R, G, and B are all\nsimilar. An RGBA (where A is alpha, or transparency) has 4 values\nper inner list, and a simple luminance image just has one value (and\nis thus only a 2-D array, not a 3-D array). For RGB and RGBA images,\nMatplotlib supports float32 and uint8 data types. For grayscale,\nMatplotlib supports only float32. If your array data does not meet\none of these descriptions, you need to rescale it.\n\n\n## Plotting numpy arrays as images\n\nSo, you have your data in a numpy array (either by importing it, or by\ngenerating it). Let's render it. In Matplotlib, this is performed\nusing the :func:`~matplotlib.pyplot.imshow` function. Here we'll grab\nthe plot object. This object gives you an easy way to manipulate the\nplot from the prompt.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "imgplot = plt.imshow(img)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also plot any numpy array.\n\n\n### Applying pseudocolor schemes to image plots\n\nPseudocolor can be a useful tool for enhancing contrast and\nvisualizing your data more easily. This is especially useful when\nmaking presentations of your data using projectors - their contrast is\ntypically quite poor.\n\nPseudocolor is only relevant to single-channel, grayscale, luminosity\nimages. We currently have an RGB image. Since R, G, and B are all\nsimilar (see for yourself above or in your data), we can just pick one\nchannel of our data using array slicing (you can read more in the\n[Numpy tutorial](https://numpy.org/doc/stable/user/quickstart.html\n#indexing-slicing-and-iterating)):\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "lum_img = img[:, :, 0]\nplt.imshow(lum_img)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, with a luminosity (2D, no color) image, the default colormap (aka lookup table,\nLUT), is applied. The default is called viridis. There are plenty of\nothers to choose from.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.imshow(lum_img, cmap=\"hot\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that you can also change colormaps on existing plot objects using the\n:meth:`~matplotlib.cm.ScalarMappable.set_cmap` method:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "imgplot = plt.imshow(lum_img)\nimgplot.set_cmap('nipy_spectral')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Note

However, remember that in the Jupyter Notebook with the inline backend,\n you can't make changes to plots that have already been rendered. If you\n create imgplot here in one cell, you cannot call set_cmap() on it in a later\n cell and expect the earlier plot to change. Make sure that you enter these\n commands together in one cell. plt commands will not change plots from earlier\n cells.

\n\nThere are many other colormap schemes available. See the `list and images\nof the colormaps`.\n\n\n### Color scale reference\n\nIt's helpful to have an idea of what value a color represents. We can\ndo that by adding a color bar to your figure:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "imgplot = plt.imshow(lum_img)\nplt.colorbar()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n### Examining a specific data range\n\nSometimes you want to enhance the contrast in your image, or expand\nthe contrast in a particular region while sacrificing the detail in\ncolors that don't vary much, or don't matter. A good tool to find\ninteresting regions is the histogram. To create a histogram of our\nimage data, we use the :func:`~matplotlib.pyplot.hist` function.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.hist(lum_img.ravel(), bins=range(256), fc='k', ec='k')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Most often, the \"interesting\" part of the image is around the peak,\nand you can get extra contrast by clipping the regions above and/or\nbelow the peak. In our histogram, it looks like there's not much\nuseful information in the high end (not many white things in the\nimage). Let's adjust the upper limit, so that we effectively \"zoom in\non\" part of the histogram. We do this by setting *clim*, the colormap\nlimits.\n\nThis can be done by passing a *clim* keyword argument in the call to\n``imshow``.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.imshow(lum_img, clim=(0, 175))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This can also be done by calling the\n:meth:`~matplotlib.cm.ScalarMappable.set_clim` method of the returned image\nplot object, but make sure that you do so in the same cell as your plot\ncommand when working with the Jupyter Notebook - it will not change\nplots from earlier cells.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "imgplot = plt.imshow(lum_img)\nimgplot.set_clim(0, 175)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n### Array Interpolation schemes\n\nInterpolation calculates what the color or value of a pixel \"should\"\nbe, according to different mathematical schemes. One common place\nthat this happens is when you resize an image. The number of pixels\nchange, but you want the same information. Since pixels are discrete,\nthere's missing space. Interpolation is how you fill that space.\nThis is why your images sometimes come out looking pixelated when you\nblow them up. The effect is more pronounced when the difference\nbetween the original image and the expanded image is greater. Let's\ntake our image and shrink it. We're effectively discarding pixels,\nonly keeping a select few. Now when we plot it, that data gets blown\nup to the size on your screen. The old pixels aren't there anymore,\nand the computer has to draw in pixels to fill that space.\n\nWe'll use the Pillow library that we used to load the image also to resize\nthe image.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "img = Image.open('../../doc/_static/stinkbug.png')\nimg.thumbnail((64, 64)) # resizes image in-place\nimgplot = plt.imshow(img)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here we use the default interpolation (\"nearest\"), since we did not\ngive :func:`~matplotlib.pyplot.imshow` any interpolation argument.\n\nLet's try some others. Here's \"bilinear\":\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "imgplot = plt.imshow(img, interpolation=\"bilinear\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and bicubic:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "imgplot = plt.imshow(img, interpolation=\"bicubic\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Bicubic interpolation is often used when blowing up photos - people\ntend to prefer blurry over pixelated.\n\n" ] } ], "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.2" } }, "nbformat": 4, "nbformat_minor": 0 }