Denoising

Tutorial denoising: This tutorial provides a comprehensive, step-by-step guide to using the bioMONAI platform for 2D microscopy image denoising tasks.

Setup imports

from bioMONAI.data import *
from bioMONAI.transforms import *
from bioMONAI.core import *
from bioMONAI.core import Path
from bioMONAI.data import get_image_files, get_target, RandomSplitter
from bioMONAI.losses import *
from bioMONAI.losses import SSIMLoss
from bioMONAI.metrics import *
from bioMONAI.datasets import download_file
import warnings
warnings.filterwarnings("ignore")
device = get_device()
print(device)
cuda

Download Data

In the next cell, we will download the dataset required for this tutorial. The dataset is hosted online, and we will use the download_file function from the bioMONAI library to download and extract the files.

  • You can change the output_directory variable to specify a different directory where you want to save the downloaded files.
  • The url variable contains the link to the dataset. If you have a different dataset, you can replace this URL with the link to your dataset.
  • By default, we are downloading only the first two images. You can modify the code to download more images if needed.

Make sure you have enough storage space in the specified directory before downloading the dataset.

# Specify the directory where you want to save the downloaded files
output_directory = "../_data/U2OS"
# Define the base URL for the dataset
url = 'http://csbdeep.bioimagecomputing.com/example_data/snr_7_binning_2.zip'

# Download only the first two images
download_file(url, output_directory, extract=True)
The file has been downloaded and saved to: /home/biagio/bioMONAI/nbs/_data/U2OS

Prepare Data for Training

In the next cell, we will prepare the data for training. We will specify the path to the training images and define the batch size and patch size. Additionally, we will apply several transformations to the images to augment the dataset and improve the model’s robustness.

  • X_path: The path to the directory containing the low-resolution training images.
  • bs: The batch size, which determines the number of images processed together in one iteration.
  • patch_size: The size of the patches to be extracted from the images.
  • itemTfms: A list of item-level transformations applied to each image, including random cropping, rotation, and flipping.
  • batchTfms: A list of batch-level transformations applied to each batch of images, including intensity scaling.
  • get_target_fn: A function to get the corresponding ground truth images for the low-resolution images.

You can customize the following parameters to suit your needs: - Change the X_path variable to point to a different dataset. - Adjust the bs and patch_size variables to match your hardware capabilities and model requirements. - Modify the transformations in itemTfms and batchTfms to include other augmentations or preprocessing steps.

After defining these parameters and transformations, we will create a BioDataLoaders object to load the training and validation datasets.

extract_directory = Path(output_directory)/'128a57f165e1044e34d9a6ef46e66b3c-snr_7_binning_2.zip.unzip'
X_path = extract_directory/'train'/'low'
batch_size = 32
patch_size = 96

get_target_fn = get_target('GT', same_filename=True, relative_path=True)

data_ops = {
    'valid_pct': 0.05,         # percentage of data for the validation set
    'seed': 42,                # seed for random number generator  
    'bs': batch_size,          # batch size
    'item_tfms': [RandCropND(patch_size),   # item transformations
                RandRot90(prob=.75), 
                RandFlip(prob=0.75)],
    'batch_tfms': [ScaleIntensityPercentiles()],   # batch transformations
}

data = BioDataLoaders.from_folder(
    X_path,                 # input images
    get_target_fn,          # target images
    show_summary=False,     # print summary of the dataset
    **data_ops,             # rest of the method arguments
    )

# print length of training and validation datasets
print('train images:', len(data.train_ds.items), '\nvalidation images:', len(data.valid_ds.items))
train images: 2335 
validation images: 122

Visualize a Batch of Training Data

In the next cell, we will visualize a batch of training data to get an idea of what the images look like after applying the transformations. This step is crucial to ensure that the data augmentation and preprocessing steps are working as expected.

  • data.show_batch(cmap='magma'): This function will display a batch of images from the training dataset using the ‘magma’ colormap.

Change the cmap parameter to use a different colormap (e.g., ‘gray’, ‘viridis’, ‘plasma’) based on your preference.

Visualizing the data helps in understanding the dataset better and ensures that the transformations are applied correctly.

data.show_batch(cmap='magma')

Visualize a Specific Image

In the next cell, we will visualize a specific image from the dataset using its index. This step is useful for inspecting individual images and verifying their quality and labels. The do_item method of the BioDataLoaders class is used to retrieve the image and its label, and the show method is used to display the image.

a=data.do_item(100)
a[0].show(cmap='magma');

Define and Train the Model

In the next cell, we will define a 2D U-Net model using the create_unet_model function from the bioMONAI library. The U-Net model is a popular architecture for image segmentation tasks, and it can be customized to suit various applications.

  • resnet34: The backbone of the U-Net model. You can replace this with other backbones like resnet18, resnet50, etc., depending on your requirements.
  • 1: The number of output channels. For grayscale images, this should be set to 1. For RGB images, set it to 3.
  • (128,128): The input size of the images. Adjust this based on the size of your input images.
  • True: Whether to use pre-trained weights for the backbone. Set this to False if you want to train the model from scratch.
  • n_in=1: The number of input channels. For grayscale images, this should be set to 1. For RGB images, set it to 3.
  • cut=7: The layer at which to cut the backbone. Adjust this based on the architecture of the backbone.

You can customize the following parameters to suit your needs: - Change the backbone to a different architecture. - Adjust the input and output channels based on your dataset. - Modify the input size to match the dimensions of your images. - Set pretrained to False if you want to train the model from scratch.

After defining the model, we will proceed to train it using the fastTrainer class. The training process involves fine-tuning the model for a specified number of epochs and evaluating its performance on the validation dataset.

from bioMONAI.nets import create_unet_model, resnet34

model = create_unet_model(resnet34, 1, (128,128), True, n_in=1, cut=7)
loss = CombinedLoss(mse_weight=0.8, mae_weight=0.1)

metrics = [MSEMetric(), MAEMetric(), SSIMMetric(2)]

trainer = fastTrainer(data, model, loss_fn=loss, metrics=metrics, show_summary=False)
trainer.fine_tune(50, freeze_epochs=2)
epoch train_loss valid_loss MSE MAE SSIM time
0 0.059404 0.028820 0.004439 0.035186 0.782493 00:05
1 0.029513 0.025047 0.002770 0.030071 0.801766 00:04

epoch train_loss valid_loss MSE MAE SSIM time
0 0.016803 0.017329 0.001759 0.022116 0.862896 00:04
1 0.016447 0.017887 0.002014 0.024195 0.861430 00:04
2 0.016174 0.022034 0.002056 0.025851 0.821955 00:04
3 0.015597 0.016985 0.001547 0.020794 0.863316 00:04
4 0.015447 0.016206 0.001710 0.021253 0.872873 00:04
5 0.015875 0.016256 0.001564 0.020914 0.870868 00:04
6 0.016107 0.019252 0.001721 0.022964 0.844214 00:04
7 0.016033 0.024780 0.001773 0.025366 0.791748 00:04
8 0.015949 0.022267 0.003057 0.029022 0.830806 00:04
9 0.015204 0.017018 0.002171 0.024134 0.871327 00:04
10 0.015618 0.018367 0.001558 0.021890 0.850685 00:04
11 0.015135 0.019554 0.002157 0.024433 0.846152 00:04
12 0.015422 0.016739 0.002041 0.023189 0.872124 00:04
13 0.014739 0.018700 0.002792 0.027068 0.862402 00:04
14 0.015263 0.021374 0.002654 0.027753 0.835249 00:04
15 0.014973 0.014822 0.001453 0.019672 0.883075 00:04
16 0.015503 0.015484 0.001514 0.020508 0.877775 00:04
17 0.014797 0.016105 0.001449 0.020097 0.870642 00:04
18 0.014278 0.019322 0.001521 0.021476 0.840421 00:04
19 0.014024 0.023237 0.001507 0.023541 0.803229 00:04
20 0.013916 0.018221 0.001477 0.021839 0.851437 00:05
21 0.013959 0.015926 0.001923 0.022371 0.878491 00:04
22 0.013830 0.016823 0.001378 0.020294 0.863092 00:04
23 0.014193 0.015493 0.001399 0.019929 0.876197 00:04
24 0.014209 0.015021 0.001452 0.020287 0.881686 00:04
25 0.013604 0.014348 0.001483 0.019813 0.888192 00:04
26 0.013010 0.017282 0.001406 0.020831 0.859263 00:04
27 0.013316 0.023020 0.001922 0.025795 0.810968 00:04
28 0.013195 0.016935 0.001397 0.020703 0.862525 00:04
29 0.013239 0.019871 0.001408 0.021163 0.833718 00:04
30 0.012697 0.016831 0.001398 0.020131 0.863003 00:04
31 0.012403 0.023011 0.002300 0.026572 0.814861 00:04
32 0.012457 0.046955 0.003461 0.046148 0.604279 00:04
33 0.012286 0.015847 0.001438 0.020022 0.873057 00:04
34 0.012017 0.015499 0.001385 0.019703 0.875795 00:05
35 0.012193 0.017920 0.001358 0.020566 0.852224 00:06
36 0.012421 0.016496 0.001453 0.020299 0.866962 00:05
37 0.012365 0.025656 0.001855 0.026656 0.784934 00:04
38 0.011899 0.018731 0.001630 0.022169 0.847904 00:04
39 0.011880 0.017276 0.001352 0.020151 0.858200 00:04
40 0.011794 0.033299 0.002153 0.032226 0.716461 00:04
41 0.012001 0.015306 0.001463 0.020122 0.878759 00:04
42 0.011601 0.020002 0.001549 0.022333 0.834702 00:04
43 0.011599 0.018692 0.001402 0.020879 0.845173 00:04
44 0.012069 0.016682 0.001308 0.019924 0.863561 00:04
45 0.011595 0.023310 0.001561 0.023929 0.803312 00:04
46 0.011469 0.028401 0.001851 0.027680 0.758474 00:04
47 0.011701 0.027342 0.001780 0.026818 0.767640 00:04
48 0.011629 0.017981 0.001374 0.020654 0.851842 00:04
49 0.011637 0.021635 0.001500 0.022693 0.818345 00:04

Show Results

In the next cell, we will visualize the results of the trained model on a batch of validation data. This step helps in understanding how well the model has learned to denoise the images.

  • trainer.show_results(cmap='magma'): This function will display a batch of images from the validation dataset along with their corresponding denoised outputs using the ‘magma’ colormap.

Visualizing the results helps in assessing the performance of the model and identifying any areas that may need further improvement.

trainer.show_results(cmap='magma')

Save the Trained Model

In the next cell, we will save the trained model to a file. This step is crucial to preserve the model’s weights and architecture, allowing you to load and use the model later without retraining it.

  • trainer.save('tmp-model'): This function saves the model to a file named ‘tmp-model’. You can change the filename to something more descriptive based on your project.

Suggestions for customization: - Change the filename to include details like the model architecture, dataset, or date (e.g., ‘unet_resnet34_U2OS_2023’). - Save the model in a specific directory by providing the full path (e.g., ‘models/unet_resnet34_U2OS_2023’). - Save additional information like training history, metrics, or configuration settings in a separate file for better reproducibility.

Saving the model ensures that you can easily share it with others or deploy it in a production environment without needing to retrain it.

trainer.save('tmp-model')
Path('../_data/U2OS/128a57f165e1044e34d9a6ef46e66b3c-snr_7_binning_2.zip.unzip/train/low/models/tmp-model.pth')

Evaluate the Model on Test Data

In the next cell, we will evaluate the performance of the trained model on unseen test data. This step is crucial to get an unbiased evaluation of the model’s performance and understand how well it generalizes to new data.

  • test_X_path: The path to the directory containing the low-resolution test images.
  • test_data: A DataLoader object created from the test images.
  • evaluate_model(trainer, test_data, metrics=SSIMMetric(2)): This function evaluates the model on the test dataset using the specified metrics (in this case, SSIM).

Suggestions for customization: - Change the test_X_path variable to point to a different test dataset. - Add more metrics to the metrics parameter to get a comprehensive evaluation (e.g., MSEMetric(), MAEMetric()). - Save the evaluation results to a file for further analysis or reporting.

Evaluating the model on test data helps in understanding its performance in real-world scenarios and identifying any areas that may need further improvement.

test_X_path = extract_directory/'test'/'low'

test_data = data.test_dl(get_image_files(test_X_path), with_labels=True)

# print length of test dataset
print('test images:', len(test_data.items))

evaluate_model(trainer, test_data, metrics=SSIMMetric(2));
test images: 615

Value
CombinedLoss
Mean 0.016343
Median 0.013684
Standard Deviation 0.012352
Min 0.000897
Max 0.103584
Q1 0.010390
Q3 0.017745

Value
SSIM
Mean 0.867367
Median 0.894554
Standard Deviation 0.114801
Min 0.125196
Max 0.992265
Q1 0.860890
Q3 0.921073

Load the Model

In this step, we will load the previously trained model using the load method of the visionTrainer class. In this example, we will:

  • Create a trainer instance and load the previously saved model.
  • Fine tune the model a several epochs more.
  • Evaluate the model with test data again.
model = create_unet_model(resnet34, 1, (128,128), True, n_in=1, cut=7)

loss = CombinedLoss(mse_weight=0.8, mae_weight=0.1)
metrics = [MSEMetric(), MAEMetric(), SSIMMetric(2)]

trainer2 = fastTrainer(data, model, loss_fn=loss, metrics=metrics, show_summary=False, find_lr=True)

# Load saved model
trainer2.load('tmp-model')

# Train several additional epochs
trainer2.fit_one_cycle(2, lr_max=2e-4)

# Evaluate the model on the test dataset
evaluate_model(trainer2, test_data, metrics=metrics, show_graph=False);
Inferred learning rate:  8e-05
epoch train_loss valid_loss MSE MAE SSIM time
0 0.011602 0.016797 0.001353 0.019897 0.862750 00:04
1 0.011909 0.017679 0.001426 0.020743 0.855363 00:04

Value
CombinedLoss
Mean 0.014925
Median 0.013315
Standard Deviation 0.009880
Min 0.000855
Max 0.098183
Q1 0.010177
Q3 0.016653
Value
MSE
Mean 0.001319
Median 0.001165
Standard Deviation 0.001026
Min 0.000002
Max 0.011593
Q1 0.000703
Q3 0.001779
Value
MAE
Mean 0.019022
Median 0.018440
Standard Deviation 0.009413
Min 0.001190
Max 0.077995
Q1 0.013614
Q3 0.024187
Value
SSIM
Mean 0.880319
Median 0.895976
Standard Deviation 0.090834
Min 0.147526
Max 0.992657
Q1 0.867129
Q3 0.922766