Skip to content

Instantly share code, notes, and snippets.

@jcreinhold
Last active May 29, 2021 19:52
Show Gist options
  • Select an option

  • Save jcreinhold/d53a693ca18b8f0673f43666ee8b0561 to your computer and use it in GitHub Desktop.

Select an option

Save jcreinhold/d53a693ca18b8f0673f43666ee8b0561 to your computer and use it in GitHub Desktop.
Working with medical images in Jupyter tutorial
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Working with medical images in Jupyter\n",
"## Jacob Reinhold\n",
"\n",
"If anaconda/[miniconda](https://docs.conda.io/en/latest/miniconda.html) isn't already installed, install it.\n",
"\n",
"Then run the [`create_env.sh` script](https://gist.github.com/jcreinhold/57ca03528916ce72914c89e5c5af4ddb) to create a working conda environment that supports all of the functionality in this notebook by running:\n",
"\n",
"```bash\n",
"source create_env.sh\n",
"```\n",
"\n",
"Now you should be able to run:\n",
"\n",
"```bash\n",
"jupyter lab\n",
"```\n",
"\n",
"in the terminal and run this notebook."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Setup"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"import os\n",
"import random\n",
"import sys\n",
"import warnings\n",
"\n",
"with warnings.catch_warnings():\n",
" warnings.filterwarnings('ignore')\n",
" import matplotlib.pyplot as plt\n",
" import nibabel as nib\n",
" import nilearn.plotting as nip\n",
" import numpy as np\n",
"\n",
" from niwidgets import NiftiWidget"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Report versions"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"numpy version: 1.20.1\n",
"matplotlib version: 3.3.4\n"
]
}
],
"source": [
"print('numpy version: {}'.format(np.__version__))\n",
"from matplotlib import __version__ as mplver\n",
"print('matplotlib version: {}'.format(mplver))"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"python version: 3.8.8\n"
]
}
],
"source": [
"pv = sys.version_info\n",
"print('python version: {}.{}.{}'.format(pv.major, pv.minor, pv.micro))"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"seed = 1337\n",
"random.seed(seed)\n",
"np.random.seed(seed)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Download an example NIfTI image"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"url = 'https://gitlab.com/jcreinhold/iacl-mni-atlas/-/raw/e4198d8f1a3baef255a30c1492b573ae9ca1bf1a/mni_icbm_152_2009c_t1_0p8mm_brain.nii.gz'\n",
"test_nifti_file = 'test.nii.gz'"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" % Total % Received % Xferd Average Speed Time Time Time Current\n",
" Dload Upload Total Spent Left Speed\n",
"100 9795k 100 9795k 0 0 11.4M 0 --:--:-- --:--:-- --:--:-- 11.4M\n"
]
}
],
"source": [
"!curl {url} --output {test_nifti_file}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Visualize the downloaded image with `niwidgets`\n",
"\n",
"(Note that I created my own version of `niwidgets` ([see here](https://github.com/jcreinhold/niwidgets)) because the original `niwidgets` package on PyPI didn't install correctly.)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<Figure size 432x288 with 0 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "393fca6657944dd0a60bc212691c7e95",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"interactive(children=(IntSlider(value=0, continuous_update=False, description='x', max=90, min=-90), IntSlider…"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"widget = NiftiWidget(test_nifti_file)\n",
"with warnings.catch_warnings():\n",
" warnings.filterwarnings('ignore', category=FutureWarning)\n",
" widget.nifti_plotter(nip.plot_anat, colormap='gray');"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Open image with `nibabel` and manipulate"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"image = nib.load(test_nifti_file)\n",
"data = image.get_fdata()"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"data **= 2. # do a trivial gamma correction"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"new_image = nib.Nifti1Image(data, image.affine, image.header, image.extra)\n",
"new_nifti_file = 'new_test.nii.gz'\n",
"new_image.to_filename(new_nifti_file)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Reopen the image and examine"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<Figure size 432x288 with 0 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "cb98428721834edd8161064fbe87842c",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"interactive(children=(IntSlider(value=0, continuous_update=False, description='x', max=90, min=-90), IntSlider…"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"widget = NiftiWidget(new_nifti_file)\n",
"with warnings.catch_warnings():\n",
" warnings.filterwarnings('ignore', category=FutureWarning)\n",
" widget.nifti_plotter(nip.plot_anat, colormap='gray');"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python [conda env:neuroimage] *",
"language": "python",
"name": "conda-env-neuroimage-py"
},
"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": 4
}
@ptohidi
Copy link

ptohidi commented May 28, 2021

Code block #7: !curl {url} instead of !curl {test_nifti_file}

@jcreinhold
Copy link
Author

Good catch. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment