{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# QC script to calculate sharpness metric for images in a plate" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following script takes an image from the OMERO server.\n", "It adds increasing levels of blurriness to it and then\n", "calculates a 'sharpness' score for the images.\n", "It highlights the start of an investigation for a workflow\n", "that might be used to identify out-of-focus images across\n", "a collection of images." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Workflow summary" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![Overview](SharpnessWorkflow.jpg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Install dependencies if required\n", "The cell below will install dependencies if you choose to run the notebook in [Google Colab](https://colab.research.google.com/notebooks/intro.ipynb#recent=true)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%pip install omero-py" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Import packages" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from skimage import feature\n", "from scipy.ndimage import convolve\n", "from scipy import misc\n", "from scipy import ndimage\n", "from ipywidgets import widgets\n", "from IPython.display import display" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Create a connection to the OMERO Server" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from omero.gateway import BlitzGateway\n", "\n", "from getpass import getpass\n", "\n", "HOST = 'wss://workshop.openmicroscopy.org/omero-ws'\n", "conn = BlitzGateway(input(\"Username: \"),\n", " getpass(\"OMERO Password: \"),\n", " host=HOST, secure=True)\n", "conn.connect()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Define the 3 algorithms we are going to test\n", "The algorithms were sourced from:\n", "* gradientBased - [stackoverflow: Detect which image is sharper](https://stackoverflow.com/questions/6646371/detect-which-image-is-sharper/26014796)\n", "* fourierBased - [Image Sharpness Measure for Blurred Images in Frequency Domain](https://doi.org/10.1016/j.proeng.2013.09.086)\n", "* edgeBased - Canny Edge Detection algorithm scipy" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "class AlgorithmList:\n", " def gradientBasedSharpnessMetric(self):\n", " gy, gx = np.gradient(plane)\n", " gnorm = np.sqrt(gx**2 + gy**2)\n", " sharpness = np.average(gnorm)\n", " return sharpness\n", "\n", " def fourierBasedSharpnessMetric(self):\n", " fftimage = np.fft.fft2(plane)\n", " fftshift = np.fft.fftshift(fftimage)\n", " fftshift = np.absolute(fftshift)\n", " M = np.amax(fftshift)\n", " Th = (fftshift > M // float(1000)).sum()\n", " if 'image' in locals():\n", " sharpness = Th // (float(image.getSizeX()) * float(image.getSizeY()))\n", " return sharpness*10000\n", " else:\n", " return Th\n", "\n", " def edgeBasedSharpnessMetric(self):\n", " edges1 = feature.canny(plane, sigma=3)\n", " kernel = np.ones((3, 3))\n", " kernel[1, 1] = 0\n", " sharpness = convolve(edges1, kernel, mode=\"constant\")\n", " sharpness = sharpness[edges1 != 0].sum()\n", " return sharpness\n", "\n", "\n", "print(\"loaded:\", dir(AlgorithmList))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Choose the algorithm to test" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def dropdown_widget(Algorithm_list,\n", " dropdown_widget_name,\n", " displaywidget=False):\n", "\n", " alg_sel = widgets.Dropdown(\n", " options=Algorithm_list,\n", " value=Algorithm_list[0],\n", " description=dropdown_widget_name,\n", " disabled=False,\n", " )\n", " if displaywidget is True:\n", " display(alg_sel)\n", " return alg_sel\n", "\n", "\n", "Algorithm = dropdown_widget(\n", " ['Gradient', 'Fourier', 'Edge'],\n", " 'Algorithm: ', True\n", ")\n", "\n", "# SELECT THE METHOD THEN MOVE TO THE NEXT CELL WITHOUT RUNNING THE CELL AGAIN" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Example Image from Scipy to test Algorithms\n", "Now create increasing levels of Gaussian blur on an image\n", "obtained from Scipy package.\n", "Calculate the sharpness of the original and blurred images\n", "using the chosen algorithm." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "method = Algorithm.value\n", "if method == 'Gradient':\n", " sharpness_method = AlgorithmList().gradientBasedSharpnessMetric\n", "elif method == 'Fourier':\n", " sharpness_method = AlgorithmList().fourierBasedSharpnessMetric\n", "elif method == 'Edge':\n", " sharpness_method = AlgorithmList().edgeBasedSharpnessMetric\n", "\n", "resultArray = np.zeros((5, 2), dtype=float)\n", "plt.figure(figsize=(20, 15))\n", "cntr = 1\n", "for sigValue in range(0, 20, 4):\n", " face = misc.face(gray=True)\n", " plane = ndimage.gaussian_filter(face, sigma=sigValue)\n", " plt.subplot(1, 5, cntr)\n", " plt.imshow(plane, cmap=plt.cm.gray)\n", " plt.axis('off')\n", " sharpness = sharpness_method()\n", " resultArray[cntr - 1, 1] = sharpness\n", " resultArray[cntr - 1, 0] = sigValue\n", " cntr = cntr + 1\n", "\n", "plt.show()\n", "plt.figure(figsize=(15, 8))\n", "plt.plot(resultArray[:, 0], resultArray[:, 1], 'ro')\n", "plt.title(method)\n", "plt.xlabel('Levels of gaussian blur')\n", "plt.ylabel('Sharpness score')\n", "plt.show()\n", "plt.gcf().clear()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Fetch OMERO Image from the server" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# ex: Select an Image and enter its Id\n", "imageId = 11270\n", "image = conn.getObject(\"Image\", imageId)\n", "print(image.getName(), image.getDescription())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now create increasing levels of Gaussian blur on an OMERO image.\n", "Calculate the sharpness of the original and blurred images using\n", "the chosen algorithm." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pixels = image.getPrimaryPixels()\n", "image_plane = pixels.getPlane(0, 0, 0)\n", "\n", "resultArray = np.zeros((5, 2), dtype=float)\n", "plt.figure(figsize=(20, 15))\n", "cntr = 1\n", "for sigValue in range(0, 20, 4):\n", " face = misc.face(gray=True)\n", " plane = ndimage.gaussian_filter(image_plane, sigma=sigValue)\n", " plt.subplot(1, 5, cntr)\n", " plt.imshow(plane, cmap=plt.cm.gray)\n", " plt.axis('off')\n", " sharpness = sharpness_method()\n", " resultArray[cntr - 1, 1] = sharpness\n", " resultArray[cntr - 1, 0] = sigValue\n", " cntr = cntr + 1\n", "\n", "plt.show()\n", "plt.figure(figsize=(15, 8))\n", "plt.plot(resultArray[:, 0], resultArray[:, 1], 'ro')\n", "plt.title(method)\n", "plt.xlabel('Levels of gaussian blur')\n", "plt.ylabel('Sharpness score')\n", "plt.show()\n", "plt.gcf().clear()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Close the connection to the OMERO server" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "conn.close()" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "### License (BSD 2-Clause)\n", "Copyright (C) 2019-2021 University of Dundee. All Rights Reserved.\n", "\n", "Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n", "\n", "Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n", "Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n", "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ] } ], "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.7.8" } }, "nbformat": 4, "nbformat_minor": 2 }