meshes = []
for part in brain_parts:
print(part['color'],part['level'])
verts, faces, normals, values = measure.marching_cubes(part['img'], part['level'])
x, y, z = verts.T
i, j, k = faces.T
complete = go.Figure(data=meshes)
complete.show() make it so that each plot is shown in a different html file
Assistant
User
import numpy as np
import plotly.graph_objects as go
import plotly.subplots as subplots
from skimage import measure
from skimage import measure
from skimage.draw import ellipsoid
import nibabel as nib
import plotly.express as px
Load brain image and segmentation
brain_path = "C:\Users\reddy\Downloads\BraTS2020_TrainingData\MICCAI_BraTS2020_TrainingData\BraTS20_Training_170\BraTS20_Training_170_flair.nii"
seg_path = "C:\Users\reddy\Downloads\BraTS2020_TrainingData\MICCAI_BraTS2020_TrainingData\BraTS20_Training_170\BraTS20_Training_170_seg.nii"
im = nib.load(brain_path).get_fdata()
seg = nib.load(seg_path).get_fdata()
Assistant
User
Assistant
User
Assistant
To display each plot in a different HTML file, you can use the write_html method of the Plotly figure object. This method allows you to save the figure as an interactive HTML file which can be viewed in any web browser.
Below is your script modified to save each plot to a separate HTML file. I've provided comments where modifications were made for clarity:
python
import numpy as np
import plotly.graph_objects as go
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from skimage import measure
from skimage.draw import ellipsoid
import nibabel as nib
import plotly.express as px
fig= plt.figure()
brain_path = "C:\\Users\\reddy\\Downloads\\BraTS2020_TrainingData\\MICCAI_BraTS2020_TrainingData\\BraTS20_Training_170\\BraTS20_Training_170_flair.nii"
seg_path = "C:\\Users\\reddy\\Downloads\\BraTS2020_TrainingData\\MICCAI_BraTS2020_TrainingData\\BraTS20_Training_170\\BraTS20_Training_170_seg.nii"
im = nib.load(brain_path).get_fdata()
seg = nib.load(seg_path).get_fdata()
brain_parts = [
{'img':im, 'color':'gray', 'level':0},
{'img':seg, 'color':'purple', 'level':0},
{'img':seg, 'color':'red', 'level':1},
{'img':seg, 'color':'yellow', 'level':2},
{'img':seg, 'color':'blue', 'level':3}
]
meshes = []
for part in brain_parts:
print(part['color'],part['level'])
verts, faces, normals, values = measure.marching_cubes(part['img'], part['level'])
x, y, z = verts.T
i, j, k = faces.T
mesh = go.Mesh3d(x=x, y=y, z=z,color=part['color'], opacity=0.5, i=i, j=j, k=k)
meshes.append(mesh)
# Full brain plot saved to HTML
full = go.Figure(data=[go.Mesh3d(x=x, y=y, z=z, opacity=0.5, i=i, j=j, k=k)])
full.write_html('full_brain.html')
# Tumor plot saved to HTML
mesh1 = go.Mesh3d(x=x, y=y, z=z,color='gray', opacity=0.5, i=i, j=j, k=k)
mesh2 = go.Mesh3d(x=x, y=y, z=z, color='yellow', opacity=0.5, i=i, j=j, k=k)
tumor = go.Figure(data=[mesh1, mesh2])
tumor.write_html('tumor.html')
# Complete plot with all parts saved to HTML
complete = go.Figure(data=meshes)
complete.write_html('complete.html')
In this updated script, the figures are first defined as before. However, instead of using the show method to display them directly within a Jupyter notebook or a Python script output, I use the write_html method to save each figure to its own HTML file. The filenames are specified directly within the method call ('full_brain.html', 'tumor.html', and 'complete.html'). You can change these filenames and paths as needed to fit your organization scheme.
Now, when you run this script, it will create three HTML files in the current working directory (or specified path): one for the full brain visualization, one for the tumor visualization, and one for the complete visualization with all brain parts. You can open these HTML files with any web browser to view your interactive 3D plots.
for mesh in meshes:
fig.add_trace(mesh, row=1, col=3)
fig.update_layout(scene_aspectmode='data')
fig.show() generate color legend for the third plot and make this into a html file
To generate a color legend for the third plot and save the figure as an HTML file, we'll need to do several things. First, since Plotly's 3D mesh plots do not directly support legends, a common workaround is to add a legend by using scatter3d plots with a single point, where each scatter plot will correspond to one of the colors we want to represent in the legend. Then, we'll update these scatter plots to create a legend effectively.
Finally, we'll use write_html method to save the figure as an HTML file.
Here's how you can do it:
python
import numpy as np
import plotly.graph_objects as go
import plotly.subplots as subplots
from skimage import measure
import nibabel as nib
# Load brain image and segmentation
brain_path = "path_to_your_data\\BraTS20_Training_170_flair.nii"
seg_path = "path_to_your_data\\BraTS20_Training_170_seg.nii"
im = nib.load(brain_path).get_fdata()
seg = nib.load(seg_path).get_fdata()
# Create a figure with three 3D subplots
fig = subplots.make_subplots(
rows=1, cols=3,
specs=[[{"type": "scene"}, {"type": "scene"}, {"type": "scene"}]],
subplot_titles=["Brain Surface", "Tumor", "Complete"]
)
# Defines for legends
legend_elements = [
{'name': 'Brain Surface', 'color': 'gray'},
{'name': 'Normal Tissue', 'color': 'purple'},
{'name': 'Edema', 'color': 'blue'},
{'name': 'Non-Enhancing Tumor', 'color': 'yellow'},
{'name': 'Enhancing Tumor', 'color': 'red'}
]
# Create meshes for different parts of the brain
brain_parts = [
{'img': im, 'color': 'gray', 'level': 0},
{'img': seg, 'color': 'purple', 'level': 0},
{'img': seg, 'color': 'blue', 'level': 1},
{'img': seg, 'color': 'yellow', 'level': 2},
{'img': seg, 'color': 'red', 'level': 3}
]
for idx, part in enumerate(brain_parts):
verts, faces, normals, values = measure.marching_cubes(part['img'], part['level'])
x, y, z = verts.T
i, j, k = faces.T
mesh = go.Mesh3d(x=x, y=y, z=z, color=part['color'], opacity=0.5, i=i, j=j, k=k,
name=legend_elements[idx]['name'], showlegend=True if idx == 0 else False)
fig.add_trace(mesh, row=1, col=3)
# Adding a point for legend
fig.add_trace(go.Scatter3d(x=[0], y=[0], z=[0], mode='markers',
marker=dict(size=10, color=part['color']),
showlegend=True, name=legend_elements[idx]['name']), row=1, col=3)
if idx == 0: # Add full mesh to Brain Surface subplot
fig.add_trace(mesh, row=1, col=1)
if 'red' in part['color']: # Add tumor mesh to Tumor subplot
fig.add_trace(mesh, row=1, col=2)
fig.update_layout(scene_aspectmode='data')
# Saving the figure as an HTML file
fig.write_html('brain_visualization.html')
In this script:
I've added scatter3d traces to the third subplot for each color legend item. Each scatter plot consists of a single point, which will not be visibly plotted due to its location but allows us to utilize the name parameter to create a legend entry effectively.
To avoid duplicate legends for identical colors, I used the showlegend parameter to only show the legend for the first occurrence.
For clarity and modularity, I restructured the loop for adding 3D meshes and legends together.
Finally, I save the entire figure as an HTML file using fig.write_html('brain_visualization.html').
Please ensure the paths to your NIfTI files are correctly set in the brain_path and seg_path variables. This script will generate a multi-subplot 3D visualization with a uniform legend for the third plot and save it as 'brain_visualization.html'.
import numpy as np
import plotly.graph_objects as go
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from skimage import measure
import nibabel as nib
import plotly.express as px
import os
import cv2
import glob
import PIL
import shutil
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from skimage import data
from skimage.util import montage
import skimage.transform as skTrans
from skimage.transform import rotate
from skimage.transform import resize
from PIL import Image, ImageOps
neural imaging
import nilearn as nl
import nibabel as nib
import nilearn.plotting as nlplt
#pip install git+https://github.com/miykael/gif_your_nifti # nifti to gif
import gif_your_nifti.core as gif2nif
from plotly.offline import plot
ml libs
import keras
import keras.backend as K
from keras.callbacks import CSVLogger
import tensorflow as tf
from keras.utils import plot_model
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from keras.models import *
from keras.layers import *
from keras.optimizers import *
from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping, TensorBoard
#from tf.keras.layers.experimental import preprocessing
meshes = []
for part in brain_parts:
print(part['color'],part['level'])
verts, faces, normals, values = measure.marching_cubes(part['img'], part['level'])
x, y, z = verts.T
i, j, k = faces.T
model = keras.models.load_model('model_per_class.h5',
custom_objects={ 'accuracy' : tf.keras.metrics.MeanIoU(num_classes=4),
"dice_coef": dice_coef,
"precision": precision,
"sensitivity":sensitivity,
"specificity":specificity,
"dice_coef_necrotic": dice_coef_necrotic,
"dice_coef_edema": dice_coef_edema,
"dice_coef_enhancing": dice_coef_enhancing
}, compile=False)
plt.show()2024-03-20 20:38:44.914220: I tensorflow/core/util/port.cc:113] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable TF_ENABLE_ONEDNN_OPTS=0.
2024-03-20 20:38:47.037510: I tensorflow/core/util/port.cc:113] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable TF_ENABLE_ONEDNN_OPTS=0.
gray 0
purple 0
red 1
yellow 2
blue 3
2024-03-20 20:38:54.412556: I tensorflow/core/platform/cpu_feature_guard.cc:210] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.
To enable the following instructions: AVX2 AVX_VNNI FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
C:\Users\reddy\AppData\Local\Programs\Python\Python312\Lib\site-packages\keras\src\optimizers\base_optimizer.py:34: UserWarning:
Argument decay is no longer supported and will be ignored.
WARNING:absl:Compiled the loaded model, but the compiled metrics have yet to be built. model.compile_metrics will be empty until you train or evaluate the model.
WARNING:absl:Error in loading the saved optimizer state. As a result, your model is starting with a freshly initialized optimizer.
This code snippet encompasses a wide variety of operations encompassing deep learning, medical image processing (especially for brain MRI images), and performance metric evaluation. The key components of the code include loading and visualizing MRI images and segmentation maps using Plotly for 3D visualization, defining custom Keras/TensorFlow metrics (such as dice coefficient, precision, sensitivity, and specificity) for model performance evaluation, and loading a pre-trained neural network model to apply these metrics.
Here are some essential takeaways and considerations:
Medical Imaging and Visualization
You're employing powerful libraries like nibabel for reading NIfTI files (a common format for medical imaging data) and skimage for image processing tasks. plotly and matplotlib are used for visualization purposes, providing an interactive and static view of the MRI scans and segmentation maps.
Neural Imaging
nilearn, albeit mentioned, doesn't seem to be directly utilized in the shared code snippet. Its primary use case is for advanced neuroimaging tasks and convenient visualization of brain volumes.
Custom Metrics with Keras/TensorFlow
The custom metrics (e.g., dice coefficient, precision, etc.) are crucial for evaluating segmentation tasks, offering insight into how well the model is performing, especially in distinguishing between different tissue types in medical images.
Potential Issues and Recommendations
Model Loading: The warning messages suggest that while the model is loaded, there's an issue with loading the optimizer state. This is primarily a concern if you plan to further train the model, as it would start with an uninitialized optimizer. Check your environment and dependencies, ensuring compatibility and correct model serialization.
Keras/TensorFlow Warning: The warning related to decay in optimizers indicates that some arguments or functionalities used might be deprecated or no longer supported in your current version of TensorFlow/Keras. Ensure your code is updated to comply with the latest version's best practices and APIs.
Reproducibility and Environment Setup: The code includes imports and functionality from a broad range of libraries. For reproducibility and ease of sharing or deployment, consider using a virtual environment and exporting your requirements.txt for Python or using Docker containers.
Error Handling and Logging: Consider adding more explicit error handling and logging throughout your code, especially where external data or complex operations are involved. This can help diagnose issues more easily and understand the code's behavior in different scenarios.
Additional Enhancements
Further Model Performance Evaluation: Beyond the custom metrics you've implemented, consider employing additional evaluation strategies, such as confusion matrices or ROC curves, for a comprehensive assessment.
Visualization Enhancements: While Plotly provides interactive 3D plots, you might explore additional visualization techniques or libraries to highlight your findings further, perhaps focusing on the regions of interest (ROI) within the brain images.
Code Organization: As the snippet encompasses a wide array of functionalities, organizing your code into modules or functions based on their purpose (e.g., data loading, visualization, model evaluation) could improve readability and maintainability.
Final Note
Your code snippet demonstrates a sophisticated approach to a complex problem, merging deep learning with medical image analysis. Going forward, ensuring compatibility between library versions, adopting best practices for newer library versions, and encapsulating functionalities could further enhance your project's quality and impact.
import os
import cv2
import glob
import PIL
import shutil
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from skimage import data
from skimage.util import montage
import skimage.transform as skTrans
from skimage.transform import rotate
from skimage.transform import resize
from PIL import Image, ImageOps
neural imaging
import nilearn as nl
import nibabel as nib
import nilearn.plotting as nlplt
!pip install git+https://github.com/miykael/gif_your_nifti # nifti to gif
import gif_your_nifti.core as gif2nif
ml libs
import keras
import keras.backend as K
from keras.callbacks import CSVLogger
import tensorflow as tf
from tensorflow.keras.utils import plot_model
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from tensorflow.keras.models import *
from tensorflow.keras.layers import *
from tensorflow.keras.optimizers import *
from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping, TensorBoard
from tensorflow.keras.layers.experimental import preprocessing
Make numpy printouts easier to read.
np.set_printoptions(precision=3, suppress=True)
DEFINE seg-areas
SEGMENT_CLASSES = {
0 : 'NOT tumor',
1 : 'NECROTIC/CORE', # or NON-ENHANCING tumor CORE
2 : 'EDEMA',
3 : 'ENHANCING' # original 4 -> converted into 3 later
}
there are 155 slices per volume
to start at 5 and use 145 slices means we will skip the first 5 and last 5
VOLUME_SLICES = 100
VOLUME_START_AT = 22 # first slice of volume that we will include
Image data descriptions
All BraTS multimodal scans are available as NIfTI files (.nii.gz) -> commonly used medical imaging format to store brain imagin data obtained using MRI and describe different MRI settings
T1: T1-weighted, native image, sagittal or axial 2D acquisitions, with 1–6 mm slice thickness.
T1c: T1-weighted, contrast-enhanced (Gadolinium) image, with 3D acquisition and 1 mm isotropic voxel size for most patients.
T2: T2-weighted image, axial 2D acquisition, with 2–6 mm slice thickness.
FLAIR: T2-weighted FLAIR image, axial, coronal, or sagittal 2D acquisitions, 2–6 mm slice thickness.
Data were acquired with different clinical protocols and various scanners from multiple (n=19) institutions.
All the imaging datasets have been segmented manually, by one to four raters, following the same annotation protocol, and their annotations were approved by experienced neuro-radiologists. Annotations comprise the GD-enhancing tumor (ET — label 4), the peritumoral edema (ED — label 2), and the necrotic and non-enhancing tumor core (NCR/NET — label 1), as described both in the BraTS 2012-2013 TMI paper and in the latest BraTS summarizing paper. The provided data are distributed after their pre-processing, i.e., co-registered to the same anatomical template, interpolated to the same resolution (1 mm^3) and skull-stripped.
nlplt.plot_roi(nimask,
title='BraTS20_Training_001_flair.nii with mask plot_roi',
bg_img=niimg,
axes=axes[3], cmap='Paired')
plt.show()
Create model || U-Net: Convolutional Networks for Biomedical Image Segmentation
he u-net is convolutional network architecture for fast and precise segmentation of images. Up to now it has outperformed the prior best method (a sliding-window convolutional network) on the ISBI challenge for segmentation of neuronal structures in electron microscopic stacks. It has won the Grand Challenge for Computer-Automated Detection of Caries in Bitewing Radiography at ISBI 2015, and it has won the Cell Tracking Challenge at ISBI 2015 on the two most challenging transmitted light microscopy categories (Phase contrast and DIC microscopy) by a large margin
more on[image: official definiton] open
Loss function
Dice coefficient
, which is essentially a measure of overlap between two samples. This measure ranges from 0 to 1 where a Dice coefficient of 1 denotes perfect and complete overlap. The Dice coefficient was originally developed for binary data, and can be calculated as:
model architecture
If you are about to use U-NET, I suggest to check out this awesome library that I found later, after manual implementation of U-NET keras-unet-collection, which also contains implementation of dice loss, tversky loss and many more!
Loading all data into memory is not a good idea since the data are too big to fit in.
So we will create dataGenerators - load data on the fly as explained here
lists of directories with studies
train_and_val_directories = [f.path for f in os.scandir(TRAIN_DATASET_PATH) if f.is_dir()]
file BraTS20_Training_355 has ill formatted name for for seg.nii file
class DataGenerator(keras.utils.Sequence):
'Generates data for Keras'
def init(self, list_IDs, dim=(IMG_SIZE,IMG_SIZE), batch_size = 1, n_channels = 2, shuffle=True):
'Initialization'
self.dim = dim
self.batch_size = batch_size
self.list_IDs = list_IDs
self.n_channels = n_channels
self.shuffle = shuffle
self.on_epoch_end()
code
def __len__(self):
'Denotes the number of batches per epoch'
return int(np.floor(len(self.list_IDs) / self.batch_size))
def __getitem__(self, index):
'Generate one batch of data'
# Generate indexes of the batch
indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]
# Find list of IDs
Batch_ids = [self.list_IDs[k] for k in indexes]
# Generate data
X, y = self.__data_generation(Batch_ids)
return X, y
def on_epoch_end(self):
'Updates indexes after each epoch'
self.indexes = np.arange(len(self.list_IDs))
if self.shuffle == True:
np.random.shuffle(self.indexes)
def __data_generation(self, Batch_ids):
'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)
# Initialization
X = np.zeros((self.batch_size*VOLUME_SLICES, *self.dim, self.n_channels))
y = np.zeros((self.batch_size*VOLUME_SLICES, 240, 240))
Y = np.zeros((self.batch_size*VOLUME_SLICES, *self.dim, 4))
# Generate data
for c, i in enumerate(Batch_ids):
case_path = os.path.join(TRAIN_DATASET_PATH, i)
data_path = os.path.join(case_path, f'{i}_flair.nii');
flair = nib.load(data_path).get_fdata()
data_path = os.path.join(case_path, f'{i}_t1ce.nii');
ce = nib.load(data_path).get_fdata()
data_path = os.path.join(case_path, f'{i}_seg.nii');
seg = nib.load(data_path).get_fdata()
for j in range(VOLUME_SLICES):
X[j +VOLUME_SLICES*c,:,:,0] = cv2.resize(flair[:,:,j+VOLUME_START_AT], (IMG_SIZE, IMG_SIZE));
X[j +VOLUME_SLICES*c,:,:,1] = cv2.resize(ce[:,:,j+VOLUME_START_AT], (IMG_SIZE, IMG_SIZE));
y[j +VOLUME_SLICES*c] = seg[:,:,j+VOLUME_START_AT];
# Generate masks
y[y==4] = 3;
mask = tf.one_hot(y, 4);
Y = tf.image.resize(mask, (IMG_SIZE, IMG_SIZE));
return X/np.max(X), Y
ax[3].plot(epoch,hist['mean_io_u'],'b',label='Training mean IOU')
ax[3].plot(epoch,hist['val_mean_io_u'],'r',label='Validation mean IOU')
ax[3].legend()
plt.show()
Prediction examples
mri type must one of 1) flair 2) t1 3) t1ce 4) t2 ------- or even 5) seg
returns volume of specified study at path
def imageLoader(path):
image = nib.load(path).get_fdata()
X = np.zeros((self.batch_sizeVOLUME_SLICES, self.dim, self.n_channels))
for j in range(VOLUME_SLICES):
X[j +VOLUME_SLICESc,:,:,0] = cv2.resize(image[:,:,j+VOLUME_START_AT], (IMG_SIZE, IMG_SIZE));
X[j +VOLUME_SLICESc,:,:,1] = cv2.resize(ce[:,:,j+VOLUME_START_AT], (IMG_SIZE, IMG_SIZE));
To run the model locally and make predictions using a pre-trained .h5 file, you'll need to follow a series of steps. First, ensure you have the necessary libraries installed in your environment. Then, you can load the model using Keras and make predictions on your data. Below is a simplified guide that outlines these steps.
Step 1: Install Required Libraries
Ensure you have the following libraries installed in your Python environment. You can install them using pip:
Note: The opencv-python-headless package is used instead of opencv-python to avoid unnecessary GUI dependencies for headless environments.
Step 2: Prepare Your Environment
Make sure you have the .h5 model file and the NIfTI files (.nii or .nii.gz) you want to predict on your local machine.
Step 3: Load the Model and Make Predictions
Here's a simplified script to load your model and make predictions on a single NIfTI file. This script assumes you have a 3D NIfTI file and you want to predict each slice of the volume. Adjust the paths and filenames accordingly.
python
import numpy as np
import nibabel as nib
import tensorflow as tf
from tensorflow.keras.models import load_model
import cv2
# Define utility functions
def preprocess_volume(img_volume, img_size=128, volume_slices=100, volume_start_at=22):
"""Preprocess the volume for prediction."""
X = np.empty((volume_slices, img_size, img_size, 2))
for j in range(volume_slices):
X[j, :, :, 0] = cv2.resize(img_volume[:, :, j + volume_start_at], (img_size, img_size))
# Assuming the second channel is similar to the first one for demonstration
X[j, :, :, 1] = cv2.resize(img_volume[:, :, j + volume_start_at], (img_size, img_size))
return X / np.max(X)
def predict_volume(model, volume):
"""Predict each slice of the volume."""
predictions = model.predict(volume, verbose=1)
return predictions
# Load your model
model_path = 'path/to/your/model.h5'
model = load_model(model_path, compile=False)
# Load a NIfTI file
nifti_path = 'path/to/your/nifti_file.nii'
img = nib.load(nifti_path).get_fdata()
# Preprocess the volume
preprocessed_volume = preprocess_volume(img)
# Make predictions
predictions = predict_volume(model, preprocessed_volume)
# Now, `predictions` contains the predicted segmentation for each slice
# You can further process `predictions` as needed
Step 4: Post-Processing Predictions
After obtaining the predictions, you might want to visualize them or convert them back into a NIfTI file for further analysis. Visualization can be done using matplotlib, and conversion to NIfTI requires setting the affine matrix correctly, which can be copied from the original NIfTI file.
Additional Notes
The script above is simplified for demonstration. Depending on your specific model architecture and the input it requires, you might need to adjust the preprocessing step.
If your model uses custom metrics or layers, you'll need to provide these to the load_model function via the custom_objects argument.
Ensure the pre-processing of the volume matches the one used during the model training phase, including normalization and resizing.
This guide should help you get started with loading a pre-trained model and making predictions on medical imaging data locally.