{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "overhead-stable",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "<ipython-input-1-a87d19a672bc>:32: DeprecationWarning: get_data() is deprecated in favor of get_fdata(), which has a more predictable return type. To obtain get_data() behavior going forward, use numpy.asanyarray(img.dataobj).\n",
      "\n",
      "* deprecated from version: 3.0\n",
      "* Will raise <class 'nibabel.deprecator.ExpiredDeprecationError'> as of version: 5.0\n",
      "  data=image.get_data()\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 252196 characters]\n",
      "text/plain": [
       "<Figure size 1000x800 with 4 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#!/usr/bin/env python3\n",
    "\n",
    "# Quick display of a Nifti image\n",
    "\n",
    "# Packages\n",
    "import nibabel as nb\n",
    "import numpy as np\n",
    "import os\n",
    "import sys\n",
    "from pathlib import Path\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "# Disable Toolbar for plots\n",
    "plt.rcParams['toolbar'] = 'None'\n",
    "\n",
    "# Environment and file names\n",
    "home = str(Path.home())\n",
    "iFile = sys.argv[1]\n",
    "oFile=(str(os.path.basename(iFile).replace('.nii.gz','.png').replace('.nii','.png')))\n",
    "\n",
    "# Set rounding\n",
    "np.set_printoptions(formatter={'float': lambda x: \"{0:0.2f}\".format(x)})\n",
    "\n",
    "\n",
    "\n",
    "### IMPORT DATA ###\n",
    "# Load data\n",
    "image=nb.load('E:/MyMasterthesis/Ref/Dataset/nifti_result/00014_FLAIR.nii')\n",
    "\n",
    "# 3D data\n",
    "if image.header['dim'][0]==3:\n",
    "    data=image.get_data()\n",
    "    # 4D data\n",
    "elif  image.header['dim'][0]==4:\n",
    "    data=image.get_data()[:,:,:,0]\n",
    "\n",
    "# Header\n",
    "header=image.header\n",
    "    \n",
    "# Set NAN to 0\n",
    "data[np.isnan(data)] = 0\n",
    "\n",
    "\n",
    "\n",
    "### PREPARE SOME PARAMETERS ###\n",
    "\n",
    "# Spacing for Aspect Ratio\n",
    "sX=header['pixdim'][1]\n",
    "sY=header['pixdim'][2]\n",
    "sZ=header['pixdim'][3]\n",
    "\n",
    "# Size per slice\n",
    "lX = data.shape[0]\n",
    "lY = data.shape[1]\n",
    "lZ = data.shape[2]\n",
    "\n",
    "# Middle slice number\n",
    "mX = int(lX/2)\n",
    "mY = int(lY/2)\n",
    "mZ = int(lZ/2)\n",
    "\n",
    "# True middle point\n",
    "tmX = lX/2.0\n",
    "tmY = lY/2.0\n",
    "tmZ = lZ/2.0\n",
    "\n",
    "\n",
    "\n",
    "### ORIENTATION ###\n",
    "qfX = image.get_qform()[0,0]\n",
    "sfX = image.get_sform()[0,0]\n",
    "\n",
    "if qfX < 0 and (sfX == 0 or sfX < 0):\n",
    "    oL = 'R'\n",
    "    oR = 'L'\n",
    "elif qfX > 0 and (sfX == 0 or sfX > 0):\n",
    "    oL = 'L'\n",
    "    oR = 'R'\n",
    "if sfX < 0 and (qfX == 0 or qfX < 0):\n",
    "    oL = 'R'\n",
    "    oR = 'L'\n",
    "elif sfX > 0 and (qfX == 0 or qfX > 0):\n",
    "    oL = 'L'\n",
    "    oR = 'R'\n",
    "\n",
    "\n",
    "\n",
    "### PLOTTING ###\n",
    "\n",
    "# Plot main window\n",
    "fig = plt.figure(\n",
    "    facecolor='black',\n",
    "    figsize=(5,4),\n",
    "    dpi=200\n",
    ")\n",
    "\n",
    "# Black background\n",
    "plt.style.use('dark_background')\n",
    "\n",
    "# Set title\n",
    "fig.canvas.set_window_title(oFile.replace('.png',''))\n",
    "\n",
    "\n",
    "# Coronal\n",
    "ax1=fig.add_subplot(2,2,1)\n",
    "imgplot = plt.imshow(\n",
    "    np.rot90(data[:,mY,:]),\n",
    "    aspect=sZ/sX,\n",
    ")\n",
    "imgplot.set_cmap('gray')\n",
    "\n",
    "ax1.hlines(tmZ, 0, lX, colors='red', linestyles='dotted', linewidth=.5)\n",
    "ax1.vlines(tmX, 0, lZ, colors='red', linestyles='dotted', linewidth=.5)\n",
    "\n",
    "plt.axis('off')\n",
    "\n",
    "\n",
    "# Sagittal\n",
    "ax2=fig.add_subplot(2,2,2)\n",
    "imgplot = plt.imshow(\n",
    "    np.rot90(data[mX,:,:]),\n",
    "    aspect=sZ/sY,\n",
    ")\n",
    "imgplot.set_cmap('gray')\n",
    "\n",
    "ax2.hlines(tmZ, 0, lY, colors='red', linestyles='dotted', linewidth=.5)\n",
    "ax2.vlines(tmY, 0, lZ, colors='red', linestyles='dotted', linewidth=.5)\n",
    "\n",
    "plt.axis('off')\n",
    "\n",
    "\n",
    "# Axial\n",
    "ax3=fig.add_subplot(2,2,3)\n",
    "imgplot = plt.imshow(\n",
    "    np.rot90(data[:,:,mZ]),\n",
    "    aspect=sY/sX\n",
    ")\n",
    "imgplot.set_cmap('gray')\n",
    "\n",
    "ax3.hlines(tmY, 0, lX, colors='red', linestyles='dotted', linewidth=.5)\n",
    "ax3.vlines(tmX, 0, lY, colors='red', linestyles='dotted', linewidth=.5)\n",
    "\n",
    "plt.axis('off')\n",
    "\n",
    "plt.text(-10, mY+5, oL, fontsize=9, color='red') # Label on left side\n",
    "\n",
    "\n",
    "# Textual information\n",
    "# sform code\n",
    "sform=np.round(image.get_sform(),decimals=2)\n",
    "sform_txt=str(sform).replace('[',' ').replace(']',' ').replace(' ','   ').replace('   -','  -')\n",
    "\n",
    "# qform code\n",
    "qform=np.round(image.get_qform(),decimals=2)\n",
    "qform_txt=str(qform).replace('[',' ').replace(']',' ').replace(' ','   ').replace('   -','  -')\n",
    "\n",
    "# Dimensions\n",
    "dims=str(data.shape).replace(', ',' x ').replace('(','').replace(')','')\n",
    "dim=(\"Dimensions: \"+dims)\n",
    "\n",
    "# Spacing\n",
    "spacing=(\"Spacing: \"\n",
    "         +str(np.round(sX, decimals=2))\n",
    "         +\" x \"\n",
    "         +str(np.round(sY, decimals=2))\n",
    "         +\" x \"\n",
    "         +str(np.round(sZ, decimals=2))\n",
    "         +\" mm\"\n",
    ")\n",
    "\n",
    "# Data type\n",
    "type=image.header.get_data_dtype()\n",
    "type_str=(\"Data type: \"+str(type))\n",
    "\n",
    "# Volumes\n",
    "volumes=(\"Volumes: \"+str(image.header['dim'][4]))\n",
    "\n",
    "# Range\n",
    "min=np.round(np.amin(data), decimals=2)\n",
    "max=np.round(np.amax(data), decimals=2)\n",
    "range=(\"Range: \"+str(min)+\" - \"+str(max))\n",
    "\n",
    "text=(\n",
    "    dim+\"\\n\"\n",
    "    +spacing+\"\\n\"\n",
    "    +volumes+\"\\n\"\n",
    "    +type_str+\"\\n\"\n",
    "    +range+\"\\n\\n\"\n",
    "    +\"sform code:\\n\"\n",
    "    +sform_txt+\"\\n\"\n",
    "    +\"\\nqform code:\\n\"\n",
    "    +qform_txt\n",
    ")\n",
    "\n",
    "# Plot text subplot\n",
    "ax4=fig.add_subplot(2,2,4)\n",
    "plt.text(\n",
    "    0.15,\n",
    "    0.95,\n",
    "    text,\n",
    "    horizontalalignment='left',\n",
    "    verticalalignment='top',\n",
    "    size=6,\n",
    "    color='white',\n",
    ")\n",
    "plt.axis('off')\n",
    "\n",
    "# Adjust whitespace\n",
    "plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)\n",
    "\n",
    "# Display\n",
    "plt.savefig('E:/MyMasterthesis/Ref/Dataset/nii')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "sporting-carroll",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
