{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Block views on images/arrays\n\nThis example illustrates the use of ``view_as_blocks`` from\n:py:func:`skimage.util`.  Block views can be incredibly useful when one\nwants to perform local operations on non-overlapping image patches.\n\nWe use ``astronaut`` from ``skimage.data`` and virtually 'slice' it into square\nblocks.  Then, on each block, we either pool the mean, the max or the\nmedian value of that block. The results are displayed altogether, along\nwith a spline interpolation of order 3 rescaling of the original `astronaut`\nimage.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nfrom scipy import ndimage as ndi\nfrom matplotlib import pyplot as plt\nimport matplotlib.cm as cm\n\nimport skimage as ski\n\n\n# get astronaut from skimage.data in grayscale\nl = ski.color.rgb2gray(ski.data.astronaut())\n\n# size of blocks\nblock_shape = (4, 4)\n\n# see astronaut as a matrix of blocks (of shape block_shape)\nview = ski.util.view_as_blocks(l, block_shape)\n\n# collapse the last two dimensions in one\nflatten_view = view.reshape(view.shape[0], view.shape[1], -1)\n\n# resampling the image by taking either the `mean`,\n# the `max` or the `median` value of each blocks.\nmean_view = np.mean(flatten_view, axis=2)\nmax_view = np.max(flatten_view, axis=2)\nmedian_view = np.median(flatten_view, axis=2)\n\n# display resampled images\nfig, axes = plt.subplots(2, 2, figsize=(8, 8), sharex=True, sharey=True)\nax = axes.ravel()\n\nl_resized = ndi.zoom(l, 2, order=3)\nax[0].set_title(\"Original rescaled with\\n spline interpolation (order=3)\")\nax[0].imshow(l_resized, extent=(-0.5, 128.5, 128.5, -0.5), cmap=cm.Greys_r)\n\nax[1].set_title(\"Block view with\\n local mean pooling\")\nax[1].imshow(mean_view, cmap=cm.Greys_r)\n\nax[2].set_title(\"Block view with\\n local max pooling\")\nax[2].imshow(max_view, cmap=cm.Greys_r)\n\nax[3].set_title(\"Block view with\\n local median pooling\")\nax[3].imshow(median_view, cmap=cm.Greys_r)\n\nfor a in ax:\n    a.set_axis_off()\n\nfig.tight_layout()\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.12.12"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}