This article follows the article about data augmentation for medical image analysis in deep learning. Here, we present a practical implementation of data preparation, and in particular data augmentation, using the TorchIO library[1].
Using code examples, we explain and illustrate the following steps:
- how to convert images to the NIfTI format
- how to create image-mask segmentation pairs
- the division of the dataset
- how to create the Dataset class
Remember that good data preparation allows the model to obtain better results. Before going into detail, let's review the image formats used for medical image analysis in deep learning.
Image formats
For the analysis of medical images in deep learning, several image formats can be found in literature, blogs and challenges. However, the format of the images used is rarely mentioned. Indeed, most of the articles indicate the imaging modality, the preprocessing steps performed and the transformations applied, but do not specify the format of the images composing the dataset.
The most popular image formats in medical imaging are: DICOM, NIfTI, and less frequently the ANALYZE and NRRD formats. The major difference between the DICOM and NIfTI formats is the information storage. In the DICOM format, the 2D slices made during acquisition are stored in separate files; whereas in the NIfTI format, they are concatenated into a volume that is saved as a single file. [2] During the various challenges presented on the Kaggle platform [3], a large number of medical images in DICOM format are converted to PNG and JPEG formats. This conversion can be done either to reduce the learning time of the network, as some competitions add a time constraint in addition to the performance constraint, or to simplify the data preparation by allowing the competitors to use tools initially developed for natural image analysis. Unfortunately, converting an image from DICOM format to JPEG or PNG format results in a significant loss of information, invisible to the human eye. This is due to the decrease in the number of gray levels contained in the image: a DICOM image is encoded on 4096 to 65536 gray levels, while a PNG or JPEG image contains only 256.
Import of libraries
First of all, let's import the libraries used for data preparation.
import os from glob import glob import dicom2nifti import pandas as pd import matplotlib.pyplot as plt import sklearn from sklearn.model_selection import train_test_split import numpy import torch import torchio as tio import torchvision import skimage from skimage import color from torch.utils.data import DataLoader
Converting images from DICOM to NIfTI format
Our images were initially saved in the DICOM format and their respective segmentation mask in NRRD format. We convert them from DICOM format to NIfTI format, as the latter is easier to handle, especially in machine learning pipelines. For this, we use the dicom2nifti library and the dicom2nifti.dicom_series_to_nifti() function.
If a "slice increment inconsistent" error is encountered during the conversion, this is due to the fact that the DICOM format allows several acquisition series to be saved in the same file folder, unlike the NIfTI format which saves one file per acquisition. However, the dicom2nifti.dicom_series_to_nifti() function does not manage multi-acquisition.
file_error = list()
# Convert DICOM to NIFTI by reporting errors
dicom_input = "../Input"
nifti_output = "../Output"
folder = glob(dicom_input + '/*')
try:
for name, patient in zip(os.listdir(dicom_input), folder):
dicom2nifti.dicom_series_to_nifti(patient, os.path.join(nifti_output, name + '.nii.gz'))
except dicom2nifti.exceptions.ConversionValidationError:
file_error.append(name)
pass
(file_error)Creation of image-mask pairs for segmentation
We use the Pandas library [4] to create the dataframe containing the paths to the dataset. This library is commonly used in data mining, as it allows to extract data from CSV files and to manipulate them easily.
# Retrieval of NIFTI paths
path_nifti = r "./Nifti"
list_nifti = []
for root , dirs, file in os.walk(path_nifti):
for name in file :
list_nifti.append(os.path.join(root, name))
df_nifti = pd.DataFrame(list(list_nifti))
df_nifti.to_csv( "./nifti_list.csv", index = False, encoding = 'utf-8-sig')
# Retrieval of mask paths
path_masks = "./masks_rate"
list_masks = []
for root , dirs, file in os.walk(path_masks):
for name in file :
list_masks.append(os.path.join(root, name))
df_masks = pd.DataFrame(list(list_masks))
df_masks.to_csv( "./"./masks_list.csv", index = False, encoding = 'utf-8-sig')
# Merge in a single table the paths of the NIFTI images and the corresponding masks
df_global = pd.DataFrame(list(zip(list_nifti, list_masks )),columns = ['nifti_list', 'masks_list'])
df_global.to_csv( "./df_global.csv", index = False, encoding = 'utf-8-sig')
print(df_global)Division of the dataset into 3 subsets
We divide the dataset into 3 subsets:
- training set: this subset contains most of the initial data (70% in this case). It’s used to estimate the parameters of the model during the training phase.
- validation set: this one is used to evaluate the performance of the model and its fit to the data during the learning phase. It often contains a smaller part of the data (20% in this case).
- test set: it measures the performance of the final model, in particular whether it has a good generalization capacity or, on the contrary, whether it is in an overfitting situation. The test set generally has a small percentage of the initial data (here 10%).
We use the scikit learn library and specifically the sklearn.model_selection.train_test_split() function [5] to split the dataset. As our dataset is balanced, we do not need to use a more sophisticated function. As we want to obtain 3 subsets, we create a custom function based on the scikit learn function. The parameters expected from the function are: the dataframe of the initial dataset, the size of the validation+test group (0.0-1.0) and the size of the test group (0.0-1.0).
def train_validation_test_split(initial_dataset, validation_test_size, test_size):
"""
Function to divide the dataset into 3 subsets: train, validation and test
Parameters
----------
initial_dataset: FLOAT
The Pandas DataFrame which contains the data.
validation_test_size: FLOAT
The proportion of the subset which will be split into the
validation and test subsets.
test_size: FLOAT
The proportion of the test subset.
Returns
-------
The train, validation and test subsets.
"""
# Splitting the initial dataset into train and validation_test sets
train, validation_test = sklearn.model_selection.train_test_split(initial_dataset, test_size = validation_test_size, random_state = True)
train.to_csv('train.csv',index = False)
Division of the validation_test set into validation and test
validation, test = sklearn.model_selection.train_test_split(validation_test, test_size = test_size, random_state = True, shuffle = True, stratify = None )
validation.to_csv('validation.csv',index = False)
test.to_csv('test.csv',index = False)
return train, validation, test# Splitting the data into train/validation/test set
train_set, validation_set, test_set =
train_validation_test_split(df_global, 0.3, 0.33)
# Checking the number of data in each subset
print('Number of data in train :', len(train_set))
print('Number of data in validation:', len(validation_set))
print('Number of data in test:', len(test_set))Import of CSV files
We import the previously generated CSV files into a Pandas dataframe with the function pandas.read_csv().
dftr = r'../DataSet/Train.csv' dataframe_train = pd.read_csv(dftr) dfte = r'../DataSet/Test.csv' dataframe_test = pd.read_csv(dfte) dfv = r'../DataSet/validation.csv' dataframe_validation = pd.read_csv(dfv)
Creation of the Dataset class
The TorchIO library is part of the PyTorch ecosystem and allows to work on volumes in the medical imaging domain. That's why we use TorchIO to create the "dataset" class to prepare the data before it is processed by the model.
# Import images and training masks and check that the number of images is equal to the number of masks
path_images_train = dataframe_train.iloc[:,0]
path_masks_train = dataframe_train.iloc[:,1]
assert len(path_images_train) == len(path_masks_train)
# Creation of a list of topics with masks and images
subjects_train = []
for path_images_train, path_masks_train in zip(path_images_train, path_masks_train):
subject_train = tio.Subject(
CT = tio.ScalarImage(path_images_train),
Segmentation = tio.LabelMap(path_masks_train),
)
subjects_train.append(subject_train)
# Definition of the list of transformations to be performed
training_transforms = tio.Compose([
tio.ToCanonical(),
tio.ZNormalization(masking_method = tio.ZNormalization.mean),
tio.OneOf({
tio.RandomAffine(degrees = 15, translation = 15): 0.5,
tio.RandomFlip(): 0.3,
tio.RandomNoise(mean = 0.6): 0.2,
})
])
# Creation of the subjects dataset class by applying the transformations
dataset_train_1 = tio.SubjectsDataset(subjects_train, transform = training_transforms)
print('Dataset size:', len(dataset_train_1), 'subjects')The dataset classes for the validation and test subsets are similar to the dataset class for the training one, except in the application of transformations. We do not apply so-called augmentation transformations (e.g. reflections, rotations, noise addition, zooming...).
# Data loading and extraction train_dataloader = DataLoader(dataset_train_1, batch_size = 1) batch_train = next(iter(train_dataloader))
Data visualization
We display the prepared data in axial slice to view the applied transformations (see article on data augmentation for medical image analysis in deep learning). We display the original image, the transformed segmentation mask and an overlay of the transformed image and mask, using the scikit-image library [6].
# collect one example image_batch = (batch_train['CT'][tio.DATA][:,:,:,::,565].squeeze()) segmentation_batch = (batch_train['segmentation'][tio.DATA][:,:,:,::,565].squeeze()) # rotate the image image_batch = torch.rot90(image_batch, 3) Segmentation_batch = torch.rot90(segmentation_batch, 3)
fig = plt.figure(figsize = (20, 15))
rows = 1
columns = 3
# Conversion from tensor to numpy.ndarray
image_batch_np = image_batch.numpy()
segmentation_batch_np = segmentation_batch.numpy()
overlay = skimage.color.label2rgb(segmentation_batch_np,image = image_batch_np, colors = [(0, 0, 0), (0.612, 0.324, 0.923)],
alpha = 0.3, bg_label = 1, bg_color = None, image_alpha = 1, kind = 'overlay')
# Image
fig.add_subplot(rows, columns, 1)
plt.imshow(image_batch_np, cmap = 'gray', origin = 'lower')
plt.axis('off')
plt.title("Image")
# Segmentation
fig.add_subplot(rows, columns, 2)
plt.imshow(segmentation_batch_np, cmap = 'gray', origin = 'lower')
plt.axis('off')
plt.title("Segmentation")
# Overlay
fig.add_subplot(rows, columns, 3)
plt.imshow(overlay, cmap = 'gray', origin = 'lower')
plt.axis('off')
plt.title("Substract")
Image and original segmentation
Horizontal reflection of the subject
Rotation of the subject
Adding Gaussian noise to the subject
Realization of a zoom on the subject
[1] F. Pérez-García, R. Sparks, and S. Ourselin. TorchIO: a Python library for efficient loading, preprocessing, augmentation and patch-based sampling of medical images in deep learning. Computer Methods and Programs in Biomedicine (June 2021), pp. 106236. ISSN: 0169-2607.doi:10.1016/j.cmpb.2021.106236.
[2] Roy, T. (2017, July). Medical Image Analysis with Deep Learning, Part 4. KDnuggets. https://www.kdnuggets.com/2017/07/medical-image-analysis-deep-learning-part-4.html
[3] SIIM-FISABIO-RSNA COVID-19 Detection | Kaggle. (2021, May). Kaggle. https://www.kaggle.com/c/siim-covid19-detection/discussion/239898
[4] Pandas development team. (2008-2021). pandas documentation - pandas 1.3.0 documentation. Pandas. https://pandas.pydata.org/docs/
[5] sklearn.model_selection.train_test_split - scikit-learn 0.24.2 documentation. Scikit-Learn.
https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html
[6] Stéfan van der Walt, Johannes L. Schönberger, Juan Nunez-Iglesias, François Boulogne, Joshua D. Warner, Neil Yager, Emmanuelle Gouillart, Tony Yu and the scikit-image contributors. scikit-image: Image processing in Python. PeerJ 2:e453 (2014) https://doi.org/10.7717/peerj.453