{ "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 characterized as a superposition of a Kikuchi diffraction pattern and a smooth background intensity.\n", "For pattern indexing, the latter intensity is undesirable, while for [virtual backscatter electron VBSE) imaging](virtual_backscatter_electron_imaging.rst), this intensity can reveal topographical, compositional or diffraction contrast.\n", "\n", "This tutorial details methods to enhance the Kikuchi diffraction pattern and manipulate detector intensities in patterns in an [EBSD](../reference/generated/kikuchipy.signals.EBSD.rst) signal.\n", "\n", "Most of the methods operating on EBSD objects use functions that operate on the individual patterns (`numpy.ndarray`).\n", "Some of these single pattern functions are available in the [kikuchipy.pattern](../reference/generated/kikuchipy.pattern.rst) 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 notebook or qt5 (from pyqt) for interactive plotting\n", "%matplotlib inline\n", "\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "\n", "import hyperspy.api as hs\n", "import kikuchipy as kp" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Use kp.load(\"data.h5\") to load your own data\n", "s = kp.data.nickel_ebsd_small()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Most methods operate inplace (indicated in their docstrings), meaning they overwrite the patterns in the EBSD signal.\n", "If we instead want to keep the original signal and operate on a new signal, we can either create a [deepcopy()](../reference/generated/kikuchipy.signals.EBSD.deepcopy.rst) 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": [ "... or pass `inplace=False` to return a new signal and keep the original signal unaffected (new in version 0.8)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's make a convenience function to plot a pattern before and after processing with the intensity distributions below.\n", "We'll also globally silence progressbars" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def plot_pattern_processing(patterns, titles):\n", " \"\"\"Plot two patterns side by side with intensity histograms below.\n", "\n", " Parameters\n", " ----------\n", " patterns : list of numpy.ndarray\n", " titles : list of str\n", " \"\"\"\n", " fig, axes = plt.subplots(2, 2, height_ratios=[3, 1.5])\n", " for ax, pattern, title in zip(axes[0], patterns, titles):\n", " ax.imshow(pattern, cmap=\"gray\")\n", " ax.set_title(title)\n", " ax.axis(\"off\")\n", " for ax, pattern in zip(axes[1], patterns):\n", " ax.hist(pattern.ravel(), bins=100)\n", " fig.tight_layout()\n", "\n", "\n", "hs.preferences.General.show_progressbar = False" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Background correction\n", "\n", "### Remove the static background\n", "\n", "Effects which are constant, like hot pixels or dirt on the detector, can be removed by subtracting or dividing by a static background wit [remove_static_background()](../reference/generated/kikuchipy.signals.EBSD.remove_static_background.rst)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "nbsphinx-thumbnail": { "tooltip": "Enhancement of Kikuchi bands in EBSD patterns" }, "tags": [ "nbsphinx-thumbnail" ] }, "outputs": [], "source": [ "s2 = s.remove_static_background(inplace=False)\n", "\n", "plot_pattern_processing(\n", " [s.inav[0, 0].data, s2.inav[0, 0].data], [\"Raw\", \"Static\"]\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We didn't have to pass a background pattern since it is stored with the currenct signal in the [static_background](../reference/generated/kikuchipy.signals.EBSD.static_background.rst) attribute.\n", "We could instead pass the background pattern in the `static_bg` parameter.\n", "\n", "The static background pattern intensity range can be scaled to each individual pattern's range prior to removal with ``scale_bg=True``." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Remove the dynamic background\n", "\n", "Uneven intensity in a static background subtracted pattern can be corrected by subtraction or division of a dynamic background pattern obtained by Gaussian blurring with [remove_dynamic_background()](../reference/generated/kikuchipy.signals.EBSD.remove_dynamic_background.rst).\n", "A Gaussian window with a standard deviation set by `std` is used to blur each pattern individually (dynamic) either in the spatial or frequency domain, set by `filter_domain`.\n", "Blurring in the frequency domain uses a low-pass [Fast Fourier Transform (FFT) filter](#Filtering-in-the-frequency-domain).\n", "Each pattern is then subtracted or divided by the individual dynamic background pattern depending on the `operation`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s3 = s2.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", " inplace=False,\n", ")\n", "\n", "plot_pattern_processing(\n", " [s2.inav[0, 0].data, s3.inav[0, 0].data], [\"Static\", \"Static + dynamic\"]\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The width of the Gaussian window is truncated at the `truncated` number of standard deviations.\n", "Output patterns are rescaled to fill the input patterns' data type range." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Get the dynamic background\n", "\n", "The Gaussian blurred pattern removed during dynamic background correction can be obtained as an EBSD signal by calling [get_dynamic_background()](../reference/generated/kikuchipy.signals.EBSD.get_dynamic_background.rst)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bg = s.get_dynamic_background(filter_domain=\"frequency\", std=8, truncate=4)\n", "\n", "plot_pattern_processing(\n", " [s.inav[0, 0].data, bg.inav[0, 0].data], [\"Raw\", \"Dynamic background\"]\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Average neighbour patterns\n", "\n", "The signal-to-noise ratio in patterns in a scan can be improved by averaging patterns with their closest neighbours within a window/kernel/mask using [average_neighbour_patterns()](../reference/generated/kikuchipy.signals.EBSD.average_neighbour_patterns.rst)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s4 = s3.average_neighbour_patterns(window=\"gaussian\", std=1, inplace=False)\n", "\n", "plot_pattern_processing(\n", " [s3.inav[0, 0].data, s4.inav[0, 0].data],\n", " [\"Static + dynamic\", \"Static + dynamic + averaged\"],\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The array of averaged patterns $g(n_{\\mathrm{x}}, n_{\\mathrm{y}})$ is obtained by spatially correlating a window $w(s, t)$ with the array of patterns $f(n_{\\mathrm{x}}, n_{\\mathrm{y}})$, here 4D, which is padded with zeros at the edges.\n", "As coordinates $n_{\\mathrm{x}}$ and $n_{\\mathrm{y}}$ are varied, the window origin moves from pattern to pattern, computing the sum of products of the window coefficients with the neighbour pattern intensities, defined by the window shape, followed by normalizing by the sum of the window coefficients.\n", "For a symmetrical window of shape $m \\times n$, this becomes 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$.\n", "The window $w$, a [Window](../reference/generated/kikuchipy.filters.Window.rst) 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()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Any 1D or 2D window with desired coefficients can be used.\n", "This custom window can be passed to the `window` parameter in [average_neighbour_patterns()](../reference/generated/kikuchipy.signals.EBSD.average_neighbour_patterns.rst) or [Window](../reference/generated/kikuchipy.filters.Window.rst) as a `numpy.ndarray` or a `dask.array.Array`.\n", "Additionally, any window in [scipy.signal.windows.get_window()](https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.get_window.html) passed as a string via `window` with the necessary parameters as keyword arguments (like `std=1` for `window=\"gaussian\"`) can be used.\n", "To demonstrate the creation and use of an asymmetrical circular window (and the use of [make_circular()](../reference/generated/kikuchipy.filters.Window.make_circular.rst), although we could create a circular window directly by calling `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.plot()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But this `(5, 4)` averaging window cannot be used with our `(3, 3)` navigation shape signal.\n", "\n", "
\n", "\n", "Note\n", " \n", "Neighbour pattern averaging increases the virtual interaction volume of the electron beam with the sample, leading to a potential loss in spatial resolution.\n", "Averaging may in some cases, like on grain boundaries, mix two or more different diffraction patterns, which might be unwanted.\n", "See Wright et al. (2015) for a discussion of this concern.\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Adaptive histogram equalization\n", "\n", "Enhancing the pattern contrast with adaptive histogram equalization has been found useful when comparing patterns for dictionary indexing Marquardt et al. (2017).\n", "With [adaptive_histogram_equalization()](../reference/generated/kikuchipy.signals.EBSD.adaptive_histogram_equalization.rst), the intensities in the pattern histogram are spread to cover the available range, e.g. [0, 255] for patterns of `uint8` data type" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s6 = s3.adaptive_histogram_equalization(kernel_size=(15, 15), inplace=False)\n", "\n", "plot_pattern_processing(\n", " [s3.inav[0, 0].data, s6.inav[0, 0].data],\n", " [\"Static + dynamic\", \"Static + dynamic + adapt. hist. eq.\"],\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `kernel_size` parameter determines the size of the contextual regions.\n", "See e.g. Fig. 5 in Jackson et al. (2019), also available via [EMsoft's GitHub repository wiki](https://github.com/EMsoft-org/EMsoft/wiki/DItutorial#52-determination-of-pattern-pre-processing-parameters), for the effect of varying `kernel_size`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Filtering in the frequency domain\n", "\n", "Filtering of patterns in the frequency domain can be done with [fft_filter()](../reference/generated/kikuchipy.signals.EBSD.fft_filter.rst).\n", "This method takes a spatial kernel defined in the spatial domain, or a transfer function defined in the frequency domain, in the `transfer_function` argument as a `numpy.ndarray` or a [Window](../reference/generated/kikuchipy.filters.Window.rst).\n", "Which domain the transfer function is defined in must be passed to the `function_domain` argument.\n", "Whether to shift zero-frequency components to the center of the FFT can also be controlled via `shift`, but note that this is only used when `function_domain=\"frequency\"`.\n", "\n", "Popular uses of filtering of EBSD patterns in the frequency domain include removing large scale variations across the detector with a Gaussian high pass filter, or removing high frequency noise with a Gaussian low pass filter.\n", "These particular functions are readily available via `Window`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pattern_shape = s.axes_manager.signal_shape[::-1]\n", "w_low = kp.filters.Window(\n", " window=\"lowpass\", cutoff=23, cutoff_width=10, shape=pattern_shape\n", ")\n", "w_high = kp.filters.Window(\n", " window=\"highpass\", cutoff=3, cutoff_width=2, shape=pattern_shape\n", ")\n", "\n", "fig, axes = plt.subplots(figsize=(9, 3), ncols=3)\n", "for ax, data, title in zip(\n", " axes, [w_low, w_high, w_low * w_high], [\"Low\", \"High\", \"Low * high\"]\n", "):\n", " im = ax.imshow(data, cmap=\"gray\")\n", " ax.set_title(title + \" filter\")\n", " fig.colorbar(im, ax=ax)\n", "fig.tight_layout()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Then, to multiply the FFT of each pattern with this transfer function, and subsequently computing the inverse FFT (IFFT), we use `fft_filter()`, and remember to shift the zero-frequency components to the centre of the FFT" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s7 = s3.fft_filter(\n", " transfer_function=w_low * w_high,\n", " function_domain=\"frequency\",\n", " shift=True,\n", " inplace=False,\n", ")\n", "\n", "plot_pattern_processing(\n", " [s3.inav[0, 0].data, s7.inav[0, 0].data],\n", " [\"Static + dynamic\", \"Static + dynamic + FFT filtered\"],\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that filtering with a spatial kernel in the frequency domain, after creating the kernel's transfer function via FFT, and computing the inverse FFT (IFFT), is, in this case, the same as spatially correlating the kernel with the pattern.\n", "\n", "Let's demonstrate this by attempting to sharpen a pattern with a Laplacian kernel in both the spatial and frequency domains and comparing the results (this is a purely illustrative example, and perhaps not that practically useful)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from scipy.ndimage import correlate\n", "\n", "\n", "# fmt: off\n", "w_laplacian = np.array([\n", " [-1, -1, -1],\n", " [-1, 8, -1],\n", " [-1, -1, -1]\n", "])\n", "# fmt: on\n", "s8 = s3.fft_filter(\n", " transfer_function=w_laplacian, function_domain=\"spatial\", inplace=False\n", ")\n", "\n", "\n", "p_filt = correlate(\n", " s3.inav[0, 0].data.astype(np.float32), weights=w_laplacian\n", ")\n", "p_filt_resc = kp.pattern.rescale_intensity(p_filt, dtype_out=np.uint8)\n", "\n", "plot_pattern_processing(\n", " [s8.inav[0, 0].data, p_filt_resc],\n", " [\"Filtered in frequency domain\", \"Filtered in spatial domain\"],\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.sum(s8.inav[0, 0].data - p_filt_resc) # Which is zero" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note also that `fft_filter()` performs the filtering on the patterns with data type `np.float32`, and therefore have to rescale back to the pattern's original data type if necessary." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Rescale intensity\n", "\n", "Vendors usually write patterns to file with 8 (`uint8`) or 16 (`uint16`) bit integer depth, holding [0, 2$^8$] or [0, 2$^{16}$] gray levels, respectively.\n", "To avoid losing intensity information when processing, we often change data types to e.g. 32 bit floating point (`float32`).\n", "However, only changing the data type with [change_dtype()](http://hyperspy.org/hyperspy-doc/current/api/hyperspy.signal.html#hyperspy.signal.BaseSignal.change_dtype) does not rescale pattern intensities, leading to patterns not using the full available data type range" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s9 = s3.deepcopy()\n", "print(s9.data.dtype, s9.data.max())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s9.change_dtype(np.uint16)\n", "print(s9.data.dtype, s9.data.max())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.figure()\n", "plt.imshow(s9.inav[0, 0].data, vmax=1000, cmap=\"gray\")\n", "plt.title(\"16-bit pixels w/ 255 as max intensity\")\n", "plt.axis(\"off\")\n", "_ = plt.colorbar()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In these cases it is convenient to rescale intensities to a desired data type range, either keeping relative intensities between patterns in a scan or not.\n", "We can do this for all patterns in an EBSD signal with [kikuchipy.signals.EBSD.rescale_intensity()](../reference/generated/kikuchipy.signals.EBSD.rescale_intensity.rst)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s9.rescale_intensity(relative=True)\n", "print(s9.data.dtype, s9.data.max())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.figure()\n", "plt.imshow(s9.inav[0, 0].data, cmap=\"gray\")\n", "plt.title(\"16-bit pixels w/ 65535 as max. intensity\")\n", "plt.axis(\"off\")\n", "_ = plt.colorbar()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Or, we can do it for a single pattern (`numpy.ndarray`) with [kikuchipy.pattern.rescale_intensity()](../reference/generated/kikuchipy.pattern.rescale_intensity.rst)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "p = s3.inav[0, 0].data\n", "print(p.min(), p.max())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "p2 = kp.pattern.rescale_intensity(p, dtype_out=np.uint16)\n", "print(p2.min(), p2.max())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also stretch the pattern contrast by removing intensities outside a range passed to `in_range` or at certain percentiles by passing percentages to `percentiles`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(s3.inav[0, 0].data.min(), s3.inav[0, 0].data.max())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s10 = s3.inav[0, 0].rescale_intensity(out_range=(10, 245), inplace=False)\n", "print(s10.data.min(), s10.data.max())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s10.rescale_intensity(percentiles=(0.5, 99.5))\n", "print(s10.data.min(), s3.data.max())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plot_pattern_processing(\n", " [s3.inav[0, 0].data, s10.data],\n", " [\"Static + dynamic\", \"Static + dynamic + clip low/high\"],\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This can reduce the influence of outliers with exceptionally high or low intensities, like hot or dead pixels." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Normalize intensity\n", "\n", "It can be useful to normalize pattern intensities to a mean value of $\\mu = 0.0$ and a standard deviation of e.g. $\\sigma = 1.0$ when e.g. comparing patterns or calculating the [image quality](feature_maps.ipynb#Image-quality).\n", "Patterns can be normalized with [normalize_intensity()](../reference/generated/kikuchipy.signals.EBSD.normalize_intensity.rst)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.mean(s3.inav[0, 0].data)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s11 = s3.inav[0, 0].normalize_intensity(num_std=1, dtype_out=np.float32, inplace=False)\n", "np.mean(s11.data)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plot_pattern_processing(\n", " [s3.inav[0, 0].data, s11.data],\n", " [\"Static + dynamic background removed\", \"Intensities normalized\"],\n", ")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.10.9" } }, "nbformat": 4, "nbformat_minor": 4 }