{ "cells": [ { "cell_type": "markdown", "metadata": { "nbsphinx": "hidden" }, "source": [ "This notebook is part of the `kikuchipy` documentation https://kikuchipy.org.\n", "Links to the documentation won't work from the notebook." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Pattern processing\n", "\n", "The raw EBSD signal can be empirically evaluated as a superposition of a Kikuchi\n", "diffraction pattern and a smooth background intensity. For pattern indexing, the\n", "latter intensity is usually undesirable, while for\n", "[virtual backscatter electron VBSE) imaging](virtual_backscatter_electron_imaging.rst),\n", "this intensity can reveal topographical, compositional or diffraction contrast.\n", "This section details methods to enhance the Kikuchi diffraction pattern and\n", "manipulate detector intensities in patterns in an\n", "[EBSD](reference.rst#kikuchipy.signals.EBSD) signal.\n", "\n", "Most of the methods operating on EBSD objects use functions that operate on the\n", "individual patterns (`numpy.ndarray`). These single pattern functions are\n", "available in the [kikuchipy.pattern](reference.rst#pattern) module.\n", "\n", "Let's import the necessary libraries and read the Nickel EBSD test data set" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# exchange inline for qt5 for interactive plotting from the pyqt package\n", "%matplotlib inline\n", "\n", "import hyperspy.api as hs\n", "import matplotlib.pyplot as plt\n", "plt.rcParams[\"font.size\"] = 15\n", "import numpy as np\n", "import kikuchipy as kp\n", "\n", "\n", "s = kp.data.nickel_ebsd_small() # Use kp.load(\"data.h5\") to load your own data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Most methods operate inplace (indicated in their docstrings), meaning they\n", "overwrite the patterns in the EBSD signal. If we instead want to keep the\n", "original signal and operate on a new signal, we can create a\n", "[deepcopy()](http://hyperspy.org/hyperspy-doc/current/api/hyperspy.signal.html#hyperspy.signal.BaseSignal.deepcopy)\n", "of the original signal. As an example here, we create a new EBSD signal from a\n", "small part of the original signal:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s2 = s.deepcopy()\n", "np.may_share_memory(s.data, s2.data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "\n", "## Background correction\n", "\n", "### Remove the static background\n", "\n", "Effects which are constant, like hot pixels or dirt on the detector, can be\n", "removed by either subtracting or dividing by a static background via\n", "[remove_static_background()](reference.rst#kikuchipy.signals.EBSD.remove_static_background):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s2.remove_static_background(operation=\"subtract\", relative=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "nbsphinx-thumbnail": { "tooltip": "Enhancement of Kikuchi bands in EBSD patterns" }, "tags": [ "nbsphinx-thumbnail" ] }, "outputs": [], "source": [ "fig, ax = plt.subplots(figsize=(13, 6), ncols=2)\n", "ax[0].imshow(s.inav[0, 0].data, cmap=\"gray\")\n", "ax[0].set_title(\"As acquired\")\n", "ax[0].axis(\"off\")\n", "ax[1].imshow(s2.inav[0, 0].data, cmap=\"gray\")\n", "ax[1].set_title(\"Static background removed\")\n", "ax[1].axis(\"off\")\n", "fig.tight_layout(w_pad=0-8)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here, the static background pattern is assumed to be stored as part of the\n", "signal `metadata`, which can be loaded via\n", "[set_experimental_parameters()](reference.rst#kikuchipy.signals.EBSD.set_experimental_parameters).\n", "The static background pattern can also be passed to the `static_bg` parameter.\n", "Passing `relative=True` (default) ensures that relative intensities between\n", "patterns are kept when they are rescaled after correction to fill the available\n", "data range. In this case, for a scan of data type `uint8` with data range\n", "[0, 255], the highest pixel intensity in a scan is stretched to 255 (and the\n", "lowest to 0), while the rest is rescaled keeping relative intensities between\n", "patterns. With `relative=False`, all patterns are stretched to [0, 255].\n", "\n", "The static background pattern intensities can be rescaled to each individual\n", "pattern's intensity range before removal by passing `scale_bg=True`, which\n", "will result in the relative intensity between patterns to be lost (passing\n", "`relative=True` along with `scale_bg=True` is not allowed)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Remove the dynamic background\n", "\n", "Uneven intensity in a static background subtracted pattern can be corrected by\n", "subtracting or dividing by a dynamic background obtained by Gaussian blurring.\n", "This so-called flat fielding is done with\n", "[remove_dynamic_background()](reference.rst#kikuchipy.signals.EBSD.remove_dynamic_background).\n", "A Gaussian window with a standard deviation set by `std` is used to blur each\n", "pattern individually (dynamic) either in the spatial or frequency domain, set by\n", "`filter_domain`. Blurring in the frequency domain is effectively accomplished\n", "by a low-pass\n", "[Fast Fourier Transform (FFT) filter](#Filtering-in-the-frequency-domain). The\n", "individual Gaussian blurred dynamic backgrounds are then subtracted or divided\n", "from the respective patterns, set by `operation`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s3 = s2.deepcopy()\n", "s3.remove_dynamic_background(\n", " operation=\"subtract\", # Default\n", " filter_domain=\"frequency\", # Default\n", " std=8, # Default is 1/8 of the pattern width\n", " truncate=4, # Default\n", ")\n", "\n", "# _ means we don't want the output\n", "_, ax = plt.subplots(figsize=(13, 6), ncols=2)\n", "ax[0].imshow(s2.inav[0, 0].data, cmap=\"gray\")\n", "ax[0].set_title(\"Static background removed\")\n", "ax[1].imshow(s3.inav[0, 0].data, cmap=\"gray\")\n", "_ = ax[1].set_title(\"Static + dynamic background removed\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The width of the Gaussian window is truncated at the `truncated` number of\n", "standard deviations. Output patterns are rescaled to fill the input patterns'\n", "data type range." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## Get the dynamic background\n", "\n", "The Gaussian blurred pattern removed during dynamic background correction can\n", "be obtained as an EBSD signal by calling\n", "[get_dynamic_background()](reference.rst#kikuchipy.signals.EBSD.get_dynamic_background):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bg = s.get_dynamic_background(filter_domain=\"frequency\", std=8, truncate=4)\n", "bg\n", "\n", "_, ax = plt.subplots(figsize=(13, 6), ncols=2)\n", "ax[0].imshow(s.inav[0, 0].data, cmap=\"gray\")\n", "ax[0].set_title(\"As acquired\")\n", "ax[1].imshow(bg.inav[0, 0].data, cmap=\"gray\")\n", "_ = ax[1].set_title(\"Dynamic background\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## Average neighbour patterns\n", "\n", "The signal-to-noise ratio in patterns in an EBSD signal `s` can be improved by\n", "averaging patterns with their closest neighbours within a window/kernel/mask\n", "with\n", "[average_neighbour_patterns()](reference.rst#kikuchipy.signals.EBSD.average_neighbour_patterns):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s4 = s3.deepcopy()\n", "s4.average_neighbour_patterns(window=\"gaussian\", std=1)\n", "\n", "_, ax = plt.subplots(figsize=(13, 6), ncols=2)\n", "ax[0].imshow(s3.inav[0, 0].data, cmap=\"gray\")\n", "ax[0].set_title(\"Static + dynamic background removed\")\n", "ax[1].imshow(s4.inav[0, 0].data, cmap=\"gray\")\n", "_ = ax[1].set_title(\"After neighbour pattern averaging\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The array of averaged patterns $g(n_{\\mathrm{x}}, n_{\\mathrm{y}})$ is obtained\n", "by spatially correlating a window $w(s, t)$ with the array of patterns\n", "$f(n_{\\mathrm{x}}, n_{\\mathrm{y}})$, here 4D, which is padded with zeros at the\n", "edges. As coordinates $n_{\\mathrm{x}}$ and $n_{\\mathrm{y}}$ are varied, the\n", "window origin moves from pattern to pattern, computing the sum of products of\n", "the window coefficients with the neighbour pattern intensities, defined by the\n", "window shape, followed by normalizing by the sum of the window coefficients. For\n", "a symmetrical window of shape $m \\times n$, this becomes\n", "Gonzalez and Woods (2017)\n", "\n", "\\begin{equation}\n", "g(n_{\\mathrm{x}}, n_{\\mathrm{y}}) =\n", "\\frac{\\sum_{s=-a}^a\\sum_{t=-b}^b{w(s, t)\n", "f(n_{\\mathrm{x}} + s, n_{\\mathrm{y}} + t)}}\n", "{\\sum_{s=-a}^a\\sum_{t=-b}^b{w(s, t)}},\n", "\\end{equation}\n", "\n", "where $a = (m - 1)/2$ and $b = (n - 1)/2$. The window $w$, a\n", "[Window](reference.rst#kikuchipy.filters.window.Window) object, can be plotted:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "w = kp.filters.Window(window=\"gaussian\", shape=(3, 3), std=1)\n", "_, _, _ = w.plot(cmap=\"inferno\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Any 1D or 2D window with desired coefficients can be used. This custom window\n", "can be passed to the `window` parameter in\n", "[average_neighbour_patterns()](reference.rst#kikuchipy.signals.EBSD.average_neighbour_patterns)\n", "or [Window](reference.rst#kikuchipy.filters.window.Window) as a `numpy.ndarray`\n", "or a `dask.array.Array`. Additionally, any window in\n", "[scipy.signal.windows.get_window()](https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.get_window.html)\n", "passed as a string via `window` with the necessary parameters as keyword\n", "arguments (like `std=1` for `window=\"gaussian\"`) can be used. To demonstrate the\n", "creation and use of an asymmetrical circular window (and the use of\n", "[make_circular()](reference.rst#kikuchipy.filters.window.Window.make_circular),\n", "although we could create a circular window directly by calling\n", "`window=\"circular\"` upon window initialization):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "w = kp.filters.Window(window=\"rectangular\", shape=(5, 4))\n", "w" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "w.make_circular()\n", "w" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s5 = s3.deepcopy()\n", "s5.average_neighbour_patterns(w)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig, im, cbar = w.plot()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But this `(5, 4)` averaging window cannot be used with our `(3, 3)` navigation\n", "shape signal." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "