{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\npynet data preprocessing\n========================\n\nCredit: A Grigis\n\npynet contains a set of tools to efficiently preprocess 3D medical images that\nis crutial for deep learning applications. It includes reorientation, bias\nfield correction, affine alignement, and intensity normalization.\n\nLoad the data\n-------------\n\nWe load the Brats dataset and select the first MRI brain image.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import os\nimport sys\nif \"CI_MODE\" in os.environ:\n    sys.exit()\n\nimport time\nimport numpy as np\nimport random\nimport nibabel\nfrom pynet.datasets import fetch_toy\nfrom pynet.preprocessing import rescale\n\ndatasetdir = \"/tmp/toy\"\ndata = fetch_toy(datasetdir=datasetdir)\nimage = nibabel.load(data.t1w_path)\ntarget = nibabel.load(data.template_path)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Define preprocessing steps\n--------------------------\n\nWe now declare MRI brain preprocessing functions that can be\ncombined with the Processor class.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from pynet.preprocessing import zscore_normalize\nfrom pynet.preprocessing import kde_normalize\nfrom pynet.preprocessing import reorient2std\nfrom pynet.preprocessing import biasfield\nfrom pynet.preprocessing import register\nfrom pynet.preprocessing import downsample\nfrom pynet.preprocessing import padd\nfrom pynet.preprocessing import scale\n\n\nsmall_image = nibabel.Nifti1Image(\n    downsample(image.get_data(), scale=4), image.affine)\nprocesses = {\n    \"zscore_normalize\": (zscore_normalize, {\"mask\": None}),\n    \"kde_normalize\": (kde_normalize, {\n        \"mask\": None, \"modality\": \"T1w\", \"norm_value\": 1}),\n    \"reorient2std\": (reorient2std, {}),\n    \"register\": (register, {\n        \"target\": small_image, \"cost\": \"corratio\", \"interp\": \"trilinear\", \"dof\": 6}),\n    \"biasfield\": (biasfield, {\"nb_iterations\": 3}),\n    \"downsample\": (downsample, {\"scale\": 2}),\n    \"padd\": (padd, {\"shape\": [256, 256, 256], \"fill_value\": 0}),\n}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Test preprocessings\n--------------------\n\nWe now apply the preprocessing steps on the loaded image. Results are\ndirectly displayed in your browser at http://localhost:8097.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from pynet.plotting import Board\n\nboard = Board(port=8097, host=\"http://localhost\", env=\"data-preprocessing\")\nfor key, (fct, kwargs) in processes.items():\n    print(\"Processing {0}...\".format(key))\n    if key in (\"reorient2std\", \"biasfield\", \"register\"):\n        normalized = fct(small_image, **kwargs).get_data()\n    else:\n        normalized = fct(small_image.get_data(), **kwargs)\n    if key in (\"padd\", \"downsample\", \"register\"):\n        images = np.expand_dims(rescale(normalized, dynamic=(0, 255)), axis=0)\n    else:\n        images = np.asarray([rescale(small_image.get_data(), dynamic=(0, 255)),\n                             rescale(normalized, dynamic=(0, 255))])\n    images = images[..., images.shape[-1] // 2]\n    images = np.expand_dims(images, axis=1)\n    board.viewer.images(\n        images, opts={\"title\": key, \"caption\": key}, win=key)\n    print(\"Done.\")\ntime.sleep(10)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Preprocessing pipeline\n----------------------\n\nWe now illustrate how we can use the Processor to preprocess the MRI\nimages. Results are directly displayed in your browser at\nhttp://localhost:8097.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from pynet.preprocessing import Processor\n\nboard = Board(port=8097, host=\"http://localhost\", env=\"data-preprocessing\")\npipeline = Processor()\npipeline.register(reorient2std, apply_to=\"image\")\npipeline.register(scale, scale=2, apply_to=\"image\")\npipeline.register(biasfield, apply_to=\"image\")\npipeline.register(register, target=target, apply_to=\"image\")\npipeline.register(zscore_normalize, apply_to=\"array\")\nkey = \"pipeline\"\nnormalized = pipeline(image)\nprint(image.shape, target.shape, normalized.shape)\nimages = np.asarray([rescale(target.get_data(), dynamic=(0, 255)),\n                     rescale(normalized.get_data(), dynamic=(0, 255))])\nimages = images[..., images.shape[-1] // 2]\nimages = np.expand_dims(images, axis=1)\nboard.viewer.images(\n    images, opts={\"title\": key, \"caption\": key}, win=key)"
      ]
    }
  ],
  "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.6.12"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}