Skip to content

Instantly share code, notes, and snippets.

@miykael
Created August 7, 2018 23:51
Show Gist options
  • Save miykael/eb81bc9ad3af495ac7ab788f2b2e865a to your computer and use it in GitHub Desktop.
Save miykael/eb81bc9ad3af495ac7ab788f2b2e865a to your computer and use it in GitHub Desktop.
Creates gifs for braindrles.us
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Import"
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {},
"outputs": [],
"source": [
"from nilearn import plotting\n",
"from nilearn import image\n",
"%matplotlib inline\n",
"import numpy as np\n",
"import nibabel as nb\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Load files"
]
},
{
"cell_type": "code",
"execution_count": 66,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Load files\n",
"sub_id = 3\n",
"filename_t1 = 'sub-%02d_t1.nii' % sub_id\n",
"filename_les = 'sub-%02d_seg.nii' % sub_id\n",
"\n",
"img_t1 = nb.load(filename_t1)\n",
"img_les = nb.load(filename_les)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Crop image intensity to 95% of values"
]
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"data = img_t1.get_data()\n",
"\n",
"threshL = np.percentile(data[data!=0], 2.5)\n",
"threshH = np.percentile(data[data!=0], 97.5)\n",
"\n",
"# Normalized image\n",
"img_norm = nb.Nifti1Image(np.clip(data, threshL, threshH),\n",
" img_t1.affine,\n",
" img_t1.header)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Compute lesion extent"
]
},
{
"cell_type": "code",
"execution_count": 68,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[42.4980011 , 22.88299561, -6.68299866]])"
]
},
"execution_count": 68,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Extent of the lesion\n",
"les_data = nb.load(filename_les).get_data()\n",
"les_extent = np.where(les_data)\n",
"min_corner = np.min(les_extent, axis=1)\n",
"step = np.ptp(les_extent, axis=1)\n",
"\n",
"# Cut coordinates (cut at 25% and 75% outside of lesion center)\n",
"coords = np.array([image.coord_transform(*list(min_corner + step * i), img_t1.affine) for i in [0.5]])\n",
"coords"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Create x, y, z view of anatmoy and lesion images"
]
},
{
"cell_type": "code",
"execution_count": 87,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"colormap = 'hsv_r'"
]
},
{
"cell_type": "code",
"execution_count": 100,
"metadata": {
"scrolled": false
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/home/line/anaconda3/lib/python3.6/site-packages/matplotlib/cbook/deprecation.py:107: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.\n",
" warnings.warn(message, mplDeprecation, stacklevel=1)\n",
"/home/line/anaconda3/lib/python3.6/site-packages/matplotlib/contour.py:902: UserWarning: linewidths is ignored by contourf\n",
" warnings.warn('linewidths is ignored by contourf')\n"
]
}
],
"source": [
"# Create anatomy images for direction x and y\n",
"figsize=(2, 2)\n",
"\n",
"for i, e in enumerate(['x', 'y']):\n",
"\n",
" plotting.plot_anat(anat_img=img_norm,\n",
" draw_cross=False,\n",
" cut_coords=coords[:, i],\n",
" display_mode=e,\n",
" annotate=False,\n",
" black_bg=True,\n",
" figure=plt.figure(figsize=figsize),\n",
" output_file='fig_anatomy_%s.png' % e)\n",
" \n",
" \"\"\"\n",
" plotting.plot_roi(img_les,\n",
" bg_img=img_norm,\n",
" draw_cross=False,\n",
" cut_coords=coords[:, i],\n",
" display_mode=e,\n",
" annotate=False,\n",
" black_bg=True,\n",
" cmap=colormap,\n",
" alpha=0.75,\n",
" figure=plt.figure(figsize=figsize),\n",
" output_file='fig_roi_%s.png' % e)\n",
" \"\"\"\n",
" plotting.plot_prob_atlas(img_les.slicer[..., None],\n",
" bg_img=img_norm,\n",
" draw_cross=False,\n",
" cut_coords=coords[:, i],\n",
" display_mode=e,\n",
" linewidths=2,\n",
" view_type='filled_contours',\n",
" annotate=False,\n",
" black_bg=True,\n",
" cmap=colormap,\n",
" alpha=0.5,\n",
" interpolation='nearest',\n",
" figure=plt.figure(figsize=figsize),\n",
" output_file='fig_roi_%s.png' % e)"
]
},
{
"cell_type": "code",
"execution_count": 101,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/home/line/anaconda3/lib/python3.6/site-packages/matplotlib/cbook/deprecation.py:107: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.\n",
" warnings.warn(message, mplDeprecation, stacklevel=1)\n",
"/home/line/anaconda3/lib/python3.6/site-packages/matplotlib/contour.py:902: UserWarning: linewidths is ignored by contourf\n",
" warnings.warn('linewidths is ignored by contourf')\n"
]
}
],
"source": [
"# Create anatomy images for direction x and y\n",
"\n",
"figsize=(4, 4)\n",
"\n",
"plotting.plot_anat(anat_img=img_norm,\n",
" draw_cross=False,\n",
" cut_coords=coords[:, 2],\n",
" display_mode='z',\n",
" annotate=False,\n",
" black_bg=True,\n",
" figure=plt.figure(figsize=figsize),\n",
" output_file='fig_anatomy_z.png')\n",
"\"\"\"\n",
"plotting.plot_roi(img_les,\n",
" bg_img=img_norm,\n",
" draw_cross=False,\n",
" cut_coords=coords[:, 2],\n",
" display_mode='z',\n",
" annotate=False,\n",
" black_bg=True,\n",
" cmap=colormap,\n",
" alpha=0.75,\n",
" figure=plt.figure(figsize=figsize),\n",
" output_file='fig_roi_z.png')\n",
"\"\"\"\n",
"plotting.plot_prob_atlas(img_les.slicer[..., None],\n",
" bg_img=img_norm,\n",
" draw_cross=False,\n",
" cut_coords=coords[:, 2],\n",
" display_mode='z',\n",
" linewidths=2,\n",
" view_type='filled_contours',\n",
" annotate=False,\n",
" black_bg=True,\n",
" cmap=colormap,\n",
" alpha=0.5,\n",
" interpolation='nearest',\n",
" figure=plt.figure(figsize=figsize),\n",
" output_file='fig_roi_z.png')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Combine everything in a nice GIF"
]
},
{
"cell_type": "code",
"execution_count": 102,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"speed = 0.5"
]
},
{
"cell_type": "code",
"execution_count": 103,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(288, 144, 4) (288, 288, 4)\n",
"(288, 144, 4) (288, 288, 4)\n"
]
}
],
"source": [
"import imageio as io\n",
"\n",
"# Load all images\n",
"gif_content = []\n",
"for s in ['anatomy', 'roi']:\n",
" row1 = np.vstack((io.imread('fig_%s_x.png' % s), (io.imread('fig_%s_y.png' % s))))\n",
" row2 = io.imread('fig_%s_z.png' % s)\n",
" \n",
" print(row1.shape, row2.shape)\n",
" rows = np.hstack((row1, row2))\n",
" gif_content.append(rows)\n",
"\n",
"io.mimsave('gif_lesion_%02d.gif' % sub_id, gif_content, duration = speed)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python [default]",
"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.4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment