# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: ELMED219
#     language: python
#     name: elmed219
# ---

# # Multiparametrisk MRI - Bildeinnlesning (a)

# Version 06.01.2020. <NAME> and <NAME>.

# # Importer biblioteker

# Dette er biblioteker vi vil bruke:

# For å vise plots direkte i notebooks:
# %matplotlib inline

# Et mye brukt plot-bibliotek:
import matplotlib
import matplotlib.pyplot as plt

# En utvidelse av matplotlib som kan generere enda penere plots:
import seaborn as sns

# Et bibliotek for effektiv manipulasjon av matriser (og mer):
import numpy as np

# For å lese, skrive og prosessere tabulære data:
import pandas as pd

# For maskinlæring:
import sklearn

# For medisinsk bildebehandling (neuro-imaging):
import nibabel

# Maskinlæring for neuro-imaging:
import nilearn

# For å lese og skrive bilder 
import imageio

# For bilde-prosessering:
import skimage

# ## `NiBabel` and `Nilearn`: Neuroimaging i Python

import nibabel as nib
import nilearn

img = nilearn.image.load_img('../testdata/0.0-test_nifti.nii.gz')

img.shape

from nibabel.viewers import OrthoSlicer3D

OrthoSlicer3D(img.get_fdata(), affine= img.affine).show()

# To ignore an unimportant warning generated by the below code 
# (remove the filter if you're curious)
import warnings 
warnings.simplefilter('ignore')

from nilearn import datasets, plotting
img = datasets.fetch_localizer_button_task()['tmap']
plotting.view_img_on_surf(img, threshold='90%', surf_mesh='fsaverage')

# ## `scikit-image`: Bildebehandling i Python

# Et eksempel fra <a href="http://scikit-image.org/docs/stable/auto_examples/color_exposure/plot_ihc_color_separation.html">scikit-image</a>-dokumentasjonen: **Immunohistochemical staining colors separation**

# +
import matplotlib.pyplot as plt

from skimage import data
from skimage.color import rgb2hed
from matplotlib.colors import LinearSegmentedColormap

# Create an artificial color close to the original one
cmap_hema = LinearSegmentedColormap.from_list('mycmap', ['white', 'navy'])
cmap_dab = LinearSegmentedColormap.from_list('mycmap', ['white',
                                             'saddlebrown'])
cmap_eosin = LinearSegmentedColormap.from_list('mycmap', ['darkviolet',
                                               'white'])

ihc_rgb = data.immunohistochemistry()
ihc_hed = rgb2hed(ihc_rgb)

fig, axes = plt.subplots(2, 2, figsize=(7, 6))
ax = axes.ravel()

ax[0].imshow(ihc_rgb)
ax[0].set_title("Original image")

ax[1].imshow(ihc_hed[:, :, 0], cmap=cmap_hema)
ax[1].set_title("Hematoxylin")

ax[2].imshow(ihc_hed[:, :, 1], cmap=cmap_eosin)
ax[2].set_title("Eosin")

ax[3].imshow(ihc_hed[:, :, 2], cmap=cmap_dab)
ax[3].set_title("DAB")

for a in ax.ravel():
    a.axis('off')

fig.tight_layout()
# -

# Manipulasjon av hematoxylin og DAB-«kanalene»:

# +
import numpy as np
from skimage.exposure import rescale_intensity

# Rescale hematoxylin and DAB signals and give them a fluorescence look
h = rescale_intensity(ihc_hed[:, :, 0], out_range=(0, 1))
d = rescale_intensity(ihc_hed[:, :, 2], out_range=(0, 1))
zdh = np.dstack((np.zeros_like(h), d, h))

fig, ax = plt.subplots()
ax.imshow(zdh)
ax.set_title("Stain separated image (rescaled)")
#ax.axis('off')
plt.show()
# -

# ## `imageio` : Python library for reading and writing image data

# Vi leser inn single-slice 4-kanals MR-bilder i DICOM-format (vi skal bruke disse dataene igjen senere i kurset)

channels = ['FLASH', 'DESS', 'FISP', 'PSIF']
nb_channels = len(channels)

images = [imageio.imread(f'../testdata/{channel.lower()}_060.dcm') for channel in channels] 

nrow, ncol = images[0].shape

# +
fig, axes = plt.subplots(2, 2, figsize=(8, 8))
ax = axes.ravel()

for i, im in enumerate(images):
    ax[i].imshow(im, cmap='gray')
    ax[i].set_title(channels[i])
    ax[i].axis('off')

plt.show()

# +
# Classes (color-coded): air, gm, wm, csf, fat, mus(cle)
train_mask = imageio.imread("../testdata/flash_060_training_mask_6cla.png")
roi_mask = imageio.imread("../testdata/flash_060_brain_mask.png")
print(train_mask.shape)

fig, axes = plt.subplots(1, 3, figsize=(10, 16), sharex=True, sharey=True)
ax = axes.ravel()
ax[0].imshow(train_mask)
ax[0].set_title("Training mask - 6 classes")
ax[1].imshow(images[0], cmap='gray')
ax[1].set_title("FLASH")
ax[2].imshow(roi_mask)
ax[2].set_title("Brain ROI")
plt.show()
# -

# Number of occurences of each unique color (class label in training mask) in descending order
from collections import Counter
Counter([tuple(colors) for i in train_mask for colors in i]).most_common()

# Count the number of occurences of oixels in ROI mask
Counter([tuple(colors) for i in roi_mask for colors in i]).most_common()



StarcoderdataJupyterScriptsDedupFiltered