Creating a Segmentation App with MONAI Deploy App SDK¶
This tutorial shows how to create an organ segmentation application for a PyTorch model that has been trained with MONAI.
Deploying AI models requires the integration with clinical imaging network, even if in a for-research-use setting. This means that the AI deploy application will need to support standards-based imaging protocols, and specifically for Radiological imaging, DICOM protocol.
Typically, DICOM network communication, either in DICOM TCP/IP network protocol or DICOMWeb, would be handled by DICOM devices or services, e.g. MONAI Deploy Informatics Gateway, so the deploy application itself would only need to use DICOM Part 10 files as input and save the AI result in DICOM Part10 file(s). For segmentation use cases, the DICOM instance file could be a DICOM Segmentation object or a DICOM RT Structure Set, and for classification, DICOM Structure Report and/or DICOM Encapsulated PDF.
During model training, input and label images are typically in non-DICOM volumetric image format, e.g., NIfTI and PNG, converted from a specific DICOM study series. Furthermore, the voxel spacings most likely have been re-sampled to be uniform for all images. When integrated with imaging networks and receiving DICOM instances from modalities and Picture Archiving and Communications System, PACS, an AI deploy application may have to deal with a whole DICOM study with multiple series, whose images’ spacing may not be the same as expected by the trained model. To address these cases consistently and efficiently, MONAI Deploy Application SDK provides classes, called operators, to parse DICOM studies, select specific series with application-defined rules, and convert the selected DICOM series into domain-specific image format along with meta-data representing the pertinent DICOM attributes.
In the following sections, we will demonstrate how to create a MONAI Deploy application package using the MONAI Deploy App SDK.
Note
For local testing, if there is a lack of DICOM Part 10 files, one can use open source programs, e.g. 3D Slicer, to convert NIfTI to DICOM files.
Creating Operators and connecting them in Application class¶
We will implement an application that consists of five Operators:
DICOMDataLoaderOperator:
Input(dicom_files): a folder path (
DataPath
)Output(dicom_study_list): a list of DICOM studies in memory (List[
DICOMStudy
])
DICOMSeriesSelectorOperator:
Input(dicom_study_list): a list of DICOM studies in memory (List[
DICOMStudy
])Input(selection_rules): a selection rule (Dict)
Output(study_selected_series_list): a DICOM series object in memory (
StudySelectedSeries
)
DICOMSeriesToVolumeOperator:
Input(study_selected_series_list): a DICOM series object in memory (
StudySelectedSeries
)Output(image): an image object in memory (
Image
)
SpleenSegOperator:
DICOMSegmentationWriterOperator:
Input(seg_image): a segmentation image object in memory (
Image
)Input(study_selected_series_list): a DICOM series object in memory (
StudySelectedSeries
)Output(dicom_seg_instance): a file path (
DataPath
)
Note
The DICOMSegmentationWriterOperator
needs both the segmentation image as well as the original DICOM series meta-data in order to use the patient demographics and the DICOM Study level attributes.
The workflow of the application would look like this.
Setup environment¶
# Install MONAI and other necessary image processing packages for the application
!python -c "import monai" || pip install -q "monai"
!python -c "import torch" || pip install -q "torch>=1.5"
!python -c "import numpy" || pip install -q "numpy>=1.21"
!python -c "import nibabel" || pip install -q "nibabel>=3.2.1"
!python -c "import pydicom" || pip install -q "pydicom>=1.4.2"
!python -c "import SimpleITK" || pip install -q "SimpleITK>=2.0.0"
!python -c "import typeguard" || pip install -q "typeguard>=2.12.1"
# Install MONAI Deploy App SDK package
!python -c "import monai.deploy" || pip install --upgrade -q "monai-deploy-app-sdk"
Note: you may need to restart the Jupyter kernel to use the updated packages.
Download/Extract ai_spleen_seg_data from Google Drive¶
# Download ai_spleen_seg_data test data zip file
!pip install gdown
!gdown "https://drive.google.com/uc?id=1GC_N8YQk_mOWN02oOzAU_2YDmNRWk--n"
# After downloading ai_spleen_seg_data zip file from the web browser or using gdown,
!unzip -o "ai_spleen_seg_data_updated_1203.zip"
Looking in indexes: https://pypi.org/simple, https://pypi.ngc.nvidia.com
Requirement already satisfied: gdown in /home/gbae/miniconda3/envs/mednist/lib/python3.6/site-packages (3.13.1)
Requirement already satisfied: six in /home/gbae/miniconda3/envs/mednist/lib/python3.6/site-packages (from gdown) (1.16.0)
Requirement already satisfied: filelock in /home/gbae/miniconda3/envs/mednist/lib/python3.6/site-packages (from gdown) (3.0.12)
Requirement already satisfied: requests[socks]>=2.12.0 in /home/gbae/miniconda3/envs/mednist/lib/python3.6/site-packages (from gdown) (2.26.0)
Requirement already satisfied: tqdm in /home/gbae/miniconda3/envs/mednist/lib/python3.6/site-packages (from gdown) (4.62.3)
Requirement already satisfied: charset-normalizer~=2.0.0 in /home/gbae/miniconda3/envs/mednist/lib/python3.6/site-packages (from requests[socks]>=2.12.0->gdown) (2.0.0)
Requirement already satisfied: certifi>=2017.4.17 in /home/gbae/miniconda3/envs/mednist/lib/python3.6/site-packages (from requests[socks]>=2.12.0->gdown) (2021.5.30)
Requirement already satisfied: idna<4,>=2.5 in /home/gbae/miniconda3/envs/mednist/lib/python3.6/site-packages (from requests[socks]>=2.12.0->gdown) (3.1)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in /home/gbae/miniconda3/envs/mednist/lib/python3.6/site-packages (from requests[socks]>=2.12.0->gdown) (1.26.6)
Requirement already satisfied: PySocks!=1.5.7,>=1.5.6 in /home/gbae/miniconda3/envs/mednist/lib/python3.6/site-packages (from requests[socks]>=2.12.0->gdown) (1.7.1)
Downloading...
From: https://drive.google.com/uc?id=1GC_N8YQk_mOWN02oOzAU_2YDmNRWk--n
To: ~/src/monai-deploy-app-sdk/notebooks/tutorials/ai_spleen_seg_data_update_1203.zip
104MB [00:10, 10.3MB/s]
Archive: ai_spleen_seg_data_updated_1203.zip
creating: dcm/
inflating: dcm/IMG0001.dcm
inflating: dcm/IMG0002.dcm
inflating: dcm/IMG0003.dcm
inflating: dcm/IMG0004.dcm
inflating: dcm/IMG0005.dcm
inflating: dcm/IMG0006.dcm
inflating: dcm/IMG0007.dcm
inflating: dcm/IMG0008.dcm
inflating: dcm/IMG0009.dcm
inflating: dcm/IMG0010.dcm
inflating: dcm/IMG0011.dcm
inflating: dcm/IMG0012.dcm
inflating: dcm/IMG0013.dcm
inflating: dcm/IMG0014.dcm
inflating: dcm/IMG0015.dcm
inflating: dcm/IMG0016.dcm
inflating: dcm/IMG0017.dcm
inflating: dcm/IMG0018.dcm
inflating: dcm/IMG0019.dcm
inflating: dcm/IMG0020.dcm
inflating: dcm/IMG0021.dcm
inflating: dcm/IMG0022.dcm
inflating: dcm/IMG0023.dcm
inflating: dcm/IMG0024.dcm
inflating: dcm/IMG0025.dcm
inflating: dcm/IMG0026.dcm
inflating: dcm/IMG0027.dcm
inflating: dcm/IMG0028.dcm
inflating: dcm/IMG0029.dcm
inflating: dcm/IMG0030.dcm
inflating: dcm/IMG0031.dcm
inflating: dcm/IMG0032.dcm
inflating: dcm/IMG0033.dcm
inflating: dcm/IMG0034.dcm
inflating: dcm/IMG0035.dcm
inflating: dcm/IMG0036.dcm
inflating: dcm/IMG0037.dcm
inflating: dcm/IMG0038.dcm
inflating: dcm/IMG0039.dcm
inflating: dcm/IMG0040.dcm
inflating: dcm/IMG0041.dcm
inflating: dcm/IMG0042.dcm
inflating: dcm/IMG0043.dcm
inflating: dcm/IMG0044.dcm
inflating: dcm/IMG0045.dcm
inflating: dcm/IMG0046.dcm
inflating: dcm/IMG0047.dcm
inflating: dcm/IMG0048.dcm
inflating: dcm/IMG0049.dcm
inflating: dcm/IMG0050.dcm
inflating: dcm/IMG0051.dcm
inflating: dcm/IMG0052.dcm
inflating: dcm/IMG0053.dcm
inflating: dcm/IMG0054.dcm
inflating: dcm/IMG0055.dcm
inflating: dcm/IMG0056.dcm
inflating: dcm/IMG0057.dcm
inflating: dcm/IMG0058.dcm
inflating: dcm/IMG0059.dcm
inflating: dcm/IMG0060.dcm
inflating: dcm/IMG0061.dcm
inflating: dcm/IMG0062.dcm
inflating: dcm/IMG0063.dcm
inflating: dcm/IMG0064.dcm
inflating: dcm/IMG0065.dcm
inflating: dcm/IMG0066.dcm
inflating: dcm/IMG0067.dcm
inflating: dcm/IMG0068.dcm
inflating: dcm/IMG0069.dcm
inflating: dcm/IMG0070.dcm
inflating: dcm/IMG0071.dcm
inflating: dcm/IMG0072.dcm
inflating: dcm/IMG0073.dcm
inflating: dcm/IMG0074.dcm
inflating: dcm/IMG0075.dcm
inflating: dcm/IMG0076.dcm
inflating: dcm/IMG0077.dcm
inflating: dcm/IMG0078.dcm
inflating: dcm/IMG0079.dcm
inflating: dcm/IMG0080.dcm
inflating: dcm/IMG0081.dcm
inflating: dcm/IMG0082.dcm
inflating: dcm/IMG0083.dcm
inflating: dcm/IMG0084.dcm
inflating: dcm/IMG0085.dcm
inflating: dcm/IMG0086.dcm
inflating: dcm/IMG0087.dcm
inflating: dcm/IMG0088.dcm
inflating: dcm/IMG0089.dcm
inflating: dcm/IMG0090.dcm
inflating: dcm/IMG0091.dcm
inflating: dcm/IMG0092.dcm
inflating: dcm/IMG0093.dcm
inflating: dcm/IMG0094.dcm
inflating: dcm/IMG0095.dcm
inflating: dcm/IMG0096.dcm
inflating: dcm/IMG0097.dcm
inflating: dcm/IMG0098.dcm
inflating: dcm/IMG0099.dcm
inflating: dcm/IMG0100.dcm
inflating: dcm/IMG0101.dcm
inflating: dcm/IMG0102.dcm
inflating: dcm/IMG0103.dcm
inflating: dcm/IMG0104.dcm
inflating: dcm/IMG0105.dcm
inflating: dcm/IMG0106.dcm
inflating: dcm/IMG0107.dcm
inflating: dcm/IMG0108.dcm
inflating: dcm/IMG0109.dcm
inflating: dcm/IMG0110.dcm
inflating: dcm/IMG0111.dcm
inflating: dcm/IMG0112.dcm
inflating: dcm/IMG0113.dcm
inflating: dcm/IMG0114.dcm
inflating: dcm/IMG0115.dcm
inflating: dcm/IMG0116.dcm
inflating: dcm/IMG0117.dcm
inflating: dcm/IMG0118.dcm
inflating: dcm/IMG0119.dcm
inflating: dcm/IMG0120.dcm
inflating: dcm/IMG0121.dcm
inflating: dcm/IMG0122.dcm
inflating: dcm/IMG0123.dcm
inflating: dcm/IMG0124.dcm
inflating: dcm/IMG0125.dcm
inflating: dcm/IMG0126.dcm
inflating: dcm/IMG0127.dcm
inflating: dcm/IMG0128.dcm
inflating: dcm/IMG0129.dcm
inflating: dcm/IMG0130.dcm
inflating: dcm/IMG0131.dcm
inflating: dcm/IMG0132.dcm
inflating: dcm/IMG0133.dcm
inflating: dcm/IMG0134.dcm
inflating: dcm/IMG0135.dcm
inflating: dcm/IMG0136.dcm
inflating: dcm/IMG0137.dcm
inflating: dcm/IMG0138.dcm
inflating: dcm/IMG0139.dcm
inflating: dcm/IMG0140.dcm
inflating: dcm/IMG0141.dcm
inflating: dcm/IMG0142.dcm
inflating: dcm/IMG0143.dcm
inflating: dcm/IMG0144.dcm
inflating: dcm/IMG0145.dcm
inflating: dcm/IMG0146.dcm
inflating: dcm/IMG0147.dcm
inflating: dcm/IMG0148.dcm
inflating: dcm/IMG0149.dcm
inflating: dcm/IMG0150.dcm
inflating: dcm/IMG0151.dcm
inflating: dcm/IMG0152.dcm
inflating: dcm/IMG0153.dcm
inflating: dcm/IMG0154.dcm
inflating: dcm/IMG0155.dcm
inflating: dcm/IMG0156.dcm
inflating: dcm/IMG0157.dcm
inflating: dcm/IMG0158.dcm
inflating: dcm/IMG0159.dcm
inflating: dcm/IMG0160.dcm
inflating: dcm/IMG0161.dcm
inflating: dcm/IMG0162.dcm
inflating: dcm/IMG0163.dcm
inflating: dcm/IMG0164.dcm
inflating: dcm/IMG0165.dcm
inflating: dcm/IMG0166.dcm
inflating: dcm/IMG0167.dcm
inflating: dcm/IMG0168.dcm
inflating: dcm/IMG0169.dcm
inflating: dcm/IMG0170.dcm
inflating: dcm/IMG0171.dcm
inflating: dcm/IMG0172.dcm
inflating: dcm/IMG0173.dcm
inflating: dcm/IMG0174.dcm
inflating: dcm/IMG0175.dcm
inflating: dcm/IMG0176.dcm
inflating: dcm/IMG0177.dcm
inflating: dcm/IMG0178.dcm
inflating: dcm/IMG0179.dcm
inflating: dcm/IMG0180.dcm
inflating: dcm/IMG0181.dcm
inflating: dcm/IMG0182.dcm
inflating: dcm/IMG0183.dcm
inflating: dcm/IMG0184.dcm
inflating: dcm/IMG0185.dcm
inflating: dcm/IMG0186.dcm
inflating: dcm/IMG0187.dcm
inflating: dcm/IMG0188.dcm
inflating: dcm/IMG0189.dcm
inflating: dcm/IMG0190.dcm
inflating: dcm/IMG0191.dcm
inflating: dcm/IMG0192.dcm
inflating: dcm/IMG0193.dcm
inflating: dcm/IMG0194.dcm
inflating: dcm/IMG0195.dcm
inflating: dcm/IMG0196.dcm
inflating: dcm/IMG0197.dcm
inflating: dcm/IMG0198.dcm
inflating: dcm/IMG0199.dcm
inflating: dcm/IMG0200.dcm
inflating: dcm/IMG0201.dcm
inflating: dcm/IMG0202.dcm
inflating: dcm/IMG0203.dcm
inflating: dcm/IMG0204.dcm
inflating: dcm/IMG0205.dcm
inflating: dcm/IMG0206.dcm
inflating: dcm/IMG0207.dcm
inflating: dcm/IMG0208.dcm
inflating: dcm/IMG0209.dcm
inflating: dcm/IMG0210.dcm
inflating: dcm/IMG0211.dcm
inflating: dcm/IMG0212.dcm
inflating: dcm/IMG0213.dcm
inflating: dcm/IMG0214.dcm
inflating: dcm/IMG0215.dcm
inflating: dcm/IMG0216.dcm
inflating: dcm/IMG0217.dcm
inflating: dcm/IMG0218.dcm
inflating: dcm/IMG0219.dcm
inflating: dcm/IMG0220.dcm
inflating: dcm/IMG0221.dcm
inflating: dcm/IMG0222.dcm
inflating: dcm/IMG0223.dcm
inflating: dcm/IMG0224.dcm
inflating: dcm/IMG0225.dcm
inflating: dcm/IMG0226.dcm
inflating: dcm/IMG0227.dcm
inflating: dcm/IMG0228.dcm
inflating: dcm/IMG0229.dcm
inflating: dcm/IMG0230.dcm
inflating: dcm/IMG0231.dcm
inflating: dcm/IMG0232.dcm
inflating: dcm/IMG0233.dcm
inflating: dcm/IMG0234.dcm
inflating: dcm/IMG0235.dcm
inflating: dcm/IMG0236.dcm
inflating: dcm/IMG0237.dcm
inflating: dcm/IMG0238.dcm
inflating: dcm/IMG0239.dcm
inflating: dcm/IMG0240.dcm
inflating: dcm/IMG0241.dcm
inflating: dcm/IMG0242.dcm
inflating: dcm/IMG0243.dcm
inflating: dcm/IMG0244.dcm
inflating: dcm/IMG0245.dcm
inflating: dcm/IMG0246.dcm
inflating: dcm/IMG0247.dcm
inflating: dcm/IMG0248.dcm
inflating: dcm/IMG0249.dcm
inflating: dcm/IMG0250.dcm
inflating: dcm/IMG0251.dcm
inflating: dcm/IMG0252.dcm
inflating: dcm/IMG0253.dcm
inflating: dcm/IMG0254.dcm
inflating: dcm/IMG0255.dcm
inflating: dcm/IMG0256.dcm
inflating: dcm/IMG0257.dcm
inflating: dcm/IMG0258.dcm
inflating: dcm/IMG0259.dcm
inflating: dcm/IMG0260.dcm
inflating: dcm/IMG0261.dcm
inflating: dcm/IMG0262.dcm
inflating: dcm/IMG0263.dcm
inflating: dcm/IMG0264.dcm
inflating: dcm/IMG0265.dcm
inflating: dcm/IMG0266.dcm
inflating: dcm/IMG0267.dcm
inflating: dcm/IMG0268.dcm
inflating: dcm/IMG0269.dcm
inflating: dcm/IMG0270.dcm
inflating: dcm/IMG0271.dcm
inflating: dcm/IMG0272.dcm
inflating: dcm/IMG0273.dcm
inflating: dcm/IMG0274.dcm
inflating: dcm/IMG0275.dcm
inflating: dcm/IMG0276.dcm
inflating: dcm/IMG0277.dcm
inflating: dcm/IMG0278.dcm
inflating: dcm/IMG0279.dcm
inflating: dcm/IMG0280.dcm
inflating: dcm/IMG0281.dcm
inflating: dcm/IMG0282.dcm
inflating: dcm/IMG0283.dcm
inflating: dcm/IMG0284.dcm
inflating: dcm/IMG0285.dcm
inflating: dcm/IMG0286.dcm
inflating: dcm/IMG0287.dcm
inflating: dcm/IMG0288.dcm
inflating: dcm/IMG0289.dcm
inflating: dcm/IMG0290.dcm
inflating: dcm/IMG0291.dcm
inflating: dcm/IMG0292.dcm
inflating: dcm/IMG0293.dcm
inflating: dcm/IMG0294.dcm
inflating: dcm/IMG0295.dcm
inflating: dcm/IMG0296.dcm
inflating: dcm/IMG0297.dcm
inflating: dcm/IMG0298.dcm
inflating: dcm/IMG0299.dcm
inflating: dcm/IMG0300.dcm
inflating: dcm/IMG0301.dcm
inflating: dcm/IMG0302.dcm
inflating: dcm/IMG0303.dcm
inflating: dcm/IMG0304.dcm
inflating: dcm/IMG0305.dcm
inflating: dcm/IMG0306.dcm
inflating: dcm/IMG0307.dcm
inflating: dcm/IMG0308.dcm
inflating: dcm/IMG0309.dcm
inflating: dcm/IMG0310.dcm
inflating: dcm/IMG0311.dcm
inflating: dcm/IMG0312.dcm
inflating: dcm/IMG0313.dcm
inflating: dcm/IMG0314.dcm
inflating: dcm/IMG0315.dcm
inflating: dcm/IMG0316.dcm
inflating: dcm/IMG0317.dcm
inflating: dcm/IMG0318.dcm
inflating: dcm/IMG0319.dcm
inflating: dcm/IMG0320.dcm
inflating: dcm/IMG0321.dcm
inflating: dcm/IMG0322.dcm
inflating: dcm/IMG0323.dcm
inflating: dcm/IMG0324.dcm
inflating: dcm/IMG0325.dcm
inflating: dcm/IMG0326.dcm
inflating: dcm/IMG0327.dcm
inflating: dcm/IMG0328.dcm
inflating: dcm/IMG0329.dcm
inflating: dcm/IMG0330.dcm
inflating: dcm/IMG0331.dcm
inflating: dcm/IMG0332.dcm
inflating: dcm/IMG0333.dcm
inflating: dcm/IMG0334.dcm
inflating: dcm/IMG0335.dcm
inflating: dcm/IMG0336.dcm
inflating: dcm/IMG0337.dcm
inflating: dcm/IMG0338.dcm
inflating: dcm/IMG0339.dcm
inflating: dcm/IMG0340.dcm
inflating: dcm/IMG0341.dcm
inflating: dcm/IMG0342.dcm
inflating: dcm/IMG0343.dcm
inflating: dcm/IMG0344.dcm
inflating: dcm/IMG0345.dcm
inflating: dcm/IMG0346.dcm
inflating: dcm/IMG0347.dcm
inflating: dcm/IMG0348.dcm
inflating: dcm/IMG0349.dcm
inflating: dcm/IMG0350.dcm
inflating: dcm/IMG0351.dcm
inflating: dcm/IMG0352.dcm
inflating: dcm/IMG0353.dcm
inflating: dcm/IMG0354.dcm
inflating: dcm/IMG0355.dcm
inflating: dcm/IMG0356.dcm
inflating: dcm/IMG0357.dcm
inflating: dcm/IMG0358.dcm
inflating: dcm/IMG0359.dcm
inflating: dcm/IMG0360.dcm
inflating: dcm/IMG0361.dcm
inflating: dcm/IMG0362.dcm
inflating: dcm/IMG0363.dcm
inflating: dcm/IMG0364.dcm
inflating: dcm/IMG0365.dcm
inflating: dcm/IMG0366.dcm
inflating: dcm/IMG0367.dcm
inflating: dcm/IMG0368.dcm
inflating: dcm/IMG0369.dcm
inflating: dcm/IMG0370.dcm
inflating: dcm/IMG0371.dcm
inflating: dcm/IMG0372.dcm
inflating: dcm/IMG0373.dcm
inflating: dcm/IMG0374.dcm
inflating: dcm/IMG0375.dcm
inflating: dcm/IMG0376.dcm
inflating: dcm/IMG0377.dcm
inflating: dcm/IMG0378.dcm
inflating: dcm/IMG0379.dcm
inflating: dcm/IMG0380.dcm
inflating: dcm/IMG0381.dcm
inflating: dcm/IMG0382.dcm
inflating: dcm/IMG0383.dcm
inflating: dcm/IMG0384.dcm
inflating: dcm/IMG0385.dcm
inflating: dcm/IMG0386.dcm
inflating: dcm/IMG0387.dcm
inflating: dcm/IMG0388.dcm
inflating: dcm/IMG0389.dcm
inflating: dcm/IMG0390.dcm
inflating: dcm/IMG0391.dcm
inflating: dcm/IMG0392.dcm
inflating: dcm/IMG0393.dcm
inflating: dcm/IMG0394.dcm
inflating: dcm/IMG0395.dcm
inflating: dcm/IMG0396.dcm
inflating: dcm/IMG0397.dcm
inflating: dcm/IMG0398.dcm
inflating: dcm/IMG0399.dcm
inflating: dcm/IMG0400.dcm
inflating: dcm/IMG0401.dcm
inflating: dcm/IMG0402.dcm
inflating: dcm/IMG0403.dcm
inflating: dcm/IMG0404.dcm
inflating: dcm/IMG0405.dcm
inflating: dcm/IMG0406.dcm
inflating: dcm/IMG0407.dcm
inflating: dcm/IMG0408.dcm
inflating: dcm/IMG0409.dcm
inflating: dcm/IMG0410.dcm
inflating: dcm/IMG0411.dcm
inflating: dcm/IMG0412.dcm
inflating: dcm/IMG0413.dcm
inflating: dcm/IMG0414.dcm
inflating: dcm/IMG0415.dcm
inflating: dcm/IMG0416.dcm
inflating: dcm/IMG0417.dcm
inflating: dcm/IMG0418.dcm
inflating: dcm/IMG0419.dcm
inflating: dcm/IMG0420.dcm
inflating: dcm/IMG0421.dcm
inflating: dcm/IMG0422.dcm
inflating: dcm/IMG0423.dcm
inflating: dcm/IMG0424.dcm
inflating: dcm/IMG0425.dcm
inflating: dcm/IMG0426.dcm
inflating: dcm/IMG0427.dcm
inflating: dcm/IMG0428.dcm
inflating: dcm/IMG0429.dcm
inflating: dcm/IMG0430.dcm
inflating: dcm/IMG0431.dcm
inflating: dcm/IMG0432.dcm
inflating: dcm/IMG0433.dcm
inflating: dcm/IMG0434.dcm
inflating: dcm/IMG0435.dcm
inflating: dcm/IMG0436.dcm
inflating: dcm/IMG0437.dcm
inflating: dcm/IMG0438.dcm
inflating: dcm/IMG0439.dcm
inflating: dcm/IMG0440.dcm
inflating: dcm/IMG0441.dcm
inflating: dcm/IMG0442.dcm
inflating: dcm/IMG0443.dcm
inflating: dcm/IMG0444.dcm
inflating: dcm/IMG0445.dcm
inflating: dcm/IMG0446.dcm
inflating: dcm/IMG0447.dcm
inflating: dcm/IMG0448.dcm
inflating: dcm/IMG0449.dcm
inflating: dcm/IMG0450.dcm
inflating: dcm/IMG0451.dcm
inflating: dcm/IMG0452.dcm
inflating: dcm/IMG0453.dcm
inflating: dcm/IMG0454.dcm
inflating: dcm/IMG0455.dcm
inflating: dcm/IMG0456.dcm
inflating: dcm/IMG0457.dcm
inflating: dcm/IMG0458.dcm
inflating: dcm/IMG0459.dcm
inflating: dcm/IMG0460.dcm
inflating: dcm/IMG0461.dcm
inflating: dcm/IMG0462.dcm
inflating: dcm/IMG0463.dcm
inflating: dcm/IMG0464.dcm
inflating: dcm/IMG0465.dcm
inflating: dcm/IMG0466.dcm
inflating: dcm/IMG0467.dcm
inflating: dcm/IMG0468.dcm
inflating: dcm/IMG0469.dcm
inflating: dcm/IMG0470.dcm
inflating: dcm/IMG0471.dcm
inflating: dcm/IMG0472.dcm
inflating: dcm/IMG0473.dcm
inflating: dcm/IMG0474.dcm
inflating: dcm/IMG0475.dcm
inflating: dcm/IMG0476.dcm
inflating: dcm/IMG0477.dcm
inflating: dcm/IMG0478.dcm
inflating: dcm/IMG0479.dcm
inflating: dcm/IMG0480.dcm
inflating: dcm/IMG0481.dcm
inflating: dcm/IMG0482.dcm
inflating: dcm/IMG0483.dcm
inflating: dcm/IMG0484.dcm
inflating: dcm/IMG0485.dcm
inflating: dcm/IMG0486.dcm
inflating: dcm/IMG0487.dcm
inflating: dcm/IMG0488.dcm
inflating: dcm/IMG0489.dcm
inflating: dcm/IMG0490.dcm
inflating: dcm/IMG0491.dcm
inflating: dcm/IMG0492.dcm
inflating: dcm/IMG0493.dcm
inflating: dcm/IMG0494.dcm
inflating: dcm/IMG0495.dcm
inflating: dcm/IMG0496.dcm
inflating: dcm/IMG0497.dcm
inflating: dcm/IMG0498.dcm
inflating: dcm/IMG0499.dcm
inflating: dcm/IMG0500.dcm
inflating: dcm/IMG0501.dcm
inflating: dcm/IMG0502.dcm
inflating: dcm/IMG0503.dcm
inflating: dcm/IMG0504.dcm
inflating: dcm/IMG0505.dcm
inflating: dcm/IMG0506.dcm
inflating: dcm/IMG0507.dcm
inflating: dcm/IMG0508.dcm
inflating: dcm/IMG0509.dcm
inflating: dcm/IMG0510.dcm
inflating: dcm/IMG0511.dcm
inflating: dcm/IMG0512.dcm
inflating: dcm/IMG0513.dcm
inflating: dcm/IMG0514.dcm
inflating: dcm/IMG0515.dcm
inflating: model.ts
Setup imports¶
Let’s import necessary classes/decorators to define Application and Operator.
import logging
from os import path
from numpy import uint8
import monai.deploy.core as md
from monai.deploy.core import ExecutionContext, Image, InputContext, IOType, Operator, OutputContext
from monai.deploy.operators.monai_seg_inference_operator import InMemImageReader, MonaiSegInferenceOperator
from monai.transforms import (
Activationsd,
AsDiscreted,
Compose,
CropForegroundd,
EnsureChannelFirstd,
Invertd,
LoadImaged,
SaveImaged,
ScaleIntensityRanged,
Spacingd,
ToTensord,
)
from monai.deploy.core import Application, resource
from monai.deploy.operators.dicom_data_loader_operator import DICOMDataLoaderOperator
from monai.deploy.operators.dicom_seg_writer_operator import DICOMSegmentationWriterOperator
from monai.deploy.operators.dicom_series_selector_operator import DICOMSeriesSelectorOperator
from monai.deploy.operators.dicom_series_to_volume_operator import DICOMSeriesToVolumeOperator
Creating Model Specific Inference Operator classes¶
Each Operator class inherits Operator class and input/output properties are specified by using @input/@output decorators.
Business logic would be implemented in the compute() method.
The App SDK provides a MonaiSegInferenceOperator
class to perform segmentation prediction with a Torch Script model. For consistency, this class uses MONAI dictionary-based transforms, as Compose
object, for pre and post transforms. The model-specific inference operator will then only need to create the pre and post transform Compose
based on what has been used in the model training and validation. Note that for deploy application, ignite
is not needed nor supported.
SpleenSegOperator¶
The SpleenSegOperator
gets as input an in-memory Image object that has been converted from a DICOM CT series by the preceding DICOMSeriesToVolumeOperator
, and as output in-memory segmentation Image object.
The pre_process
function creates the pre-transforms Compose
object. For LoadImage
, a specialized InMemImageReader
, derived from MONAI ImageReader
, is used to convert the in-memory pixel data and return the numpy
array as well as the meta-data. Also, the DICOM input pixel spacings are often not the same as expected by the model, so the Spacingd
transform must be used to re-sample the image with the expected spacing.
The post_process
function creates the post-transform Compose
object. The SaveImageD
transform class is used to save the segmentation mask as NIfTI image file, which is optional as the in-memory mask image will be passed down to the DICOM Segmentation writer for creating a DICOM Segmentation instance. The Invertd
must also be used to revert the segmentation image’s orientation and spacing to be the same as the input.
When the MonaiSegInferenceOperator
object is created, the ROI
size is specified, as well as the transform Compose
objects. Furthermore, the dataset image key names are set accordingly.
Loading of the model and performing the prediction are encapsulated in the MonaiSegInferenceOperator
and other SDK classes. Once the inference is completed, the segmentation Image object is created and set to the output (op_output.set(value, label)), by the MonaiSegInferenceOperator
.
@md.input("image", Image, IOType.IN_MEMORY)
@md.output("seg_image", Image, IOType.IN_MEMORY)
@md.env(pip_packages=["monai>=0.8.1", "torch>=1.5", "numpy>=1.21", "nibabel"])
class SpleenSegOperator(Operator):
"""Performs Spleen segmentation with a 3D image converted from a DICOM CT series.
"""
def __init__(self):
self.logger = logging.getLogger("{}.{}".format(__name__, type(self).__name__))
super().__init__()
self._input_dataset_key = "image"
self._pred_dataset_key = "pred"
def compute(self, op_input: InputContext, op_output: OutputContext, context: ExecutionContext):
input_image = op_input.get("image")
if not input_image:
raise ValueError("Input image is not found.")
output_path = context.output.get().path
# This operator gets an in-memory Image object, so a specialized ImageReader is needed.
_reader = InMemImageReader(input_image)
pre_transforms = self.pre_process(_reader)
post_transforms = self.post_process(pre_transforms, path.join(output_path, "prediction_output"))
# Delegates inference and saving output to the built-in operator.
infer_operator = MonaiSegInferenceOperator(
(
160,
160,
160,
),
pre_transforms,
post_transforms,
)
# Setting the keys used in the dictironary based transforms may change.
infer_operator.input_dataset_key = self._input_dataset_key
infer_operator.pred_dataset_key = self._pred_dataset_key
# Now let the built-in operator handles the work with the I/O spec and execution context.
infer_operator.compute(op_input, op_output, context)
def pre_process(self, img_reader) -> Compose:
"""Composes transforms for preprocessing input before predicting on a model."""
my_key = self._input_dataset_key
return Compose(
[
LoadImaged(keys=my_key, reader=img_reader),
EnsureChannelFirstd(keys=my_key),
Spacingd(keys=my_key, pixdim=[1.0, 1.0, 1.0], mode=["bilinear"], align_corners=True),
ScaleIntensityRanged(keys=my_key, a_min=-57, a_max=164, b_min=0.0, b_max=1.0, clip=True),
CropForegroundd(keys=my_key, source_key=my_key),
ToTensord(keys=my_key),
]
)
def post_process(self, pre_transforms: Compose, out_dir: str = "./prediction_output") -> Compose:
"""Composes transforms for postprocessing the prediction results."""
pred_key = self._pred_dataset_key
return Compose(
[
Activationsd(keys=pred_key, softmax=True),
AsDiscreted(keys=pred_key, argmax=True),
Invertd(
keys=pred_key, transform=pre_transforms, orig_keys=self._input_dataset_key, nearest_interp=True
),
SaveImaged(keys=pred_key, output_dir=out_dir, output_postfix="seg", output_dtype=uint8, resample=False),
]
)
Creating Application class¶
Our application class would look like below.
It defines App
class, inheriting Application class.
The requirements (resource and package dependency) for the App can be specified by using @resource and @env decorators.
The base class method, compose
, is overridden. Objects required for DICOM parsing, series selection (selecting the first series for the current release), pixel data conversion to volume image, and segmentation instance creation are created, so is the model-specific SpleenSegOperator
. The execution pipeline, as a Directed Acyclic Graph, is created by connecting these objects through self.add_flow().
@resource(cpu=1, gpu=1, memory="7Gi")
class AISpleenSegApp(Application):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def compose(self):
study_loader_op = DICOMDataLoaderOperator()
series_selector_op = DICOMSeriesSelectorOperator()
series_to_vol_op = DICOMSeriesToVolumeOperator()
# Creates DICOM Seg writer with segment label name in a string list
dicom_seg_writer = DICOMSegmentationWriterOperator(seg_labels=["Spleen"])
# Creates the model specific segmentation operator
spleen_seg_op = SpleenSegOperator()
# Creates the DAG by linking the operators
self.add_flow(study_loader_op, series_selector_op, {"dicom_study_list": "dicom_study_list"})
self.add_flow(series_selector_op, series_to_vol_op, {"study_selected_series_list": "study_selected_series_list"})
self.add_flow(series_to_vol_op, spleen_seg_op, {"image": "image"})
self.add_flow(series_selector_op, dicom_seg_writer, {"study_selected_series_list": "study_selected_series_list"})
self.add_flow(spleen_seg_op, dicom_seg_writer, {"seg_image": "seg_image"})
Executing app locally¶
We can execute the app in the Jupyter notebook. Note that the DICOM files of the CT Abdomen series must be present in the dcm
and the Torch Script model at model.ts
. Please use the actual path in your environment.
app = AISpleenSegApp()
app.run(input="dcm", output="output", model="model.ts")
Going to initiate execution of operator DICOMDataLoaderOperator
Executing operator DICOMDataLoaderOperator (Process ID: 999862, Operator ID: c04e9506-86e0-4675-8f7c-698ede56a3e6)
[2021-11-24 15:29:08,591] [WARNING] (root) - No selection rules given; select all series.
[2021-11-24 15:29:08,591] [INFO] (root) - Working on study, instance UID: 1.2.826.0.1.3680043.2.1125.1.67295333199898911264201812221946213
[2021-11-24 15:29:08,592] [INFO] (root) - Working on series, instance UID: 1.2.826.0.1.3680043.2.1125.1.68102559796966796813942775094416763
Done performing execution of operator DICOMDataLoaderOperator
Going to initiate execution of operator DICOMSeriesSelectorOperator
Executing operator DICOMSeriesSelectorOperator (Process ID: 999862, Operator ID: 8cd97116-305b-492f-8d51-13864d3108e2)
Working on study, instance UID: 1.2.826.0.1.3680043.2.1125.1.67295333199898911264201812221946213
Working on series, instance UID: 1.2.826.0.1.3680043.2.1125.1.68102559796966796813942775094416763
Done performing execution of operator DICOMSeriesSelectorOperator
Going to initiate execution of operator DICOMSeriesToVolumeOperator
Executing operator DICOMSeriesToVolumeOperator (Process ID: 999862, Operator ID: a5ab0fb9-6a54-4fef-9f77-056531cce7e7)
Done performing execution of operator DICOMSeriesToVolumeOperator
Going to initiate execution of operator SpleenSegOperator
Executing operator SpleenSegOperator (Process ID: 999862, Operator ID: 65c122dd-aca1-4de2-9757-067c4fb5562d)
Converted Image object metadata:
SeriesInstanceUID: 1.2.826.0.1.3680043.2.1125.1.68102559796966796813942775094416763, type <class 'str'>
Modality: CT, type <class 'str'>
SeriesDescription: No series description, type <class 'str'>
PatientPosition: HFS, type <class 'str'>
SeriesNumber: 1, type <class 'int'>
row_pixel_spacing: 1.0, type <class 'float'>
col_pixel_spacing: 1.0, type <class 'float'>
depth_pixel_spacing: 1.0, type <class 'float'>
row_direction_cosine: [-1.0, 0.0, 0.0], type <class 'list'>
col_direction_cosine: [0.0, -1.0, 0.0], type <class 'list'>
depth_direction_cosine: [0.0, 0.0, 1.0], type <class 'list'>
dicom_affine_transform: [[-1. 0. 0. 0.]
[ 0. -1. 0. 0.]
[ 0. 0. 1. 0.]
[ 0. 0. 0. 1.]], type <class 'numpy.ndarray'>
nifti_affine_transform: [[ 1. -0. -0. -0.]
[-0. 1. -0. -0.]
[ 0. 0. 1. 0.]
[ 0. 0. 0. 1.]], type <class 'numpy.ndarray'>
StudyInstanceUID: 1.2.826.0.1.3680043.2.1125.1.67295333199898911264201812221946213, type <class 'str'>
StudyID: SLICER10001, type <class 'str'>
StudyDate: 2019-09-16, type <class 'str'>
StudyTime: 010100.000000, type <class 'str'>
StudyDescription: spleen, type <class 'str'>
AccessionNumber: 1, type <class 'str'>
selection_name: 1.2.826.0.1.3680043.2.1125.1.68102559796966796813942775094416763, type <class 'str'>
[2021-11-24 15:29:18,697] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - Number of DICOM instance datasets in the list: 515
[2021-11-24 15:29:18,698] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - Number of slices in the numpy image: 515
[2021-11-24 15:29:18,698] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - Labels of the segments: ['Spleen']
file written: ~/src/monai-deploy-app-sdk/notebooks/tutorials/output/prediction_output/1.2.826.0.1.3680043.2.1125.1/1.2.826.0.1.3680043.2.1125.1_seg.nii.gz.
Output Seg image numpy array shaped: (515, 440, 440)
Output Seg image pixel max value: 1
Done performing execution of operator SpleenSegOperator
Going to initiate execution of operator DICOMSegmentationWriterOperator
Executing operator DICOMSegmentationWriterOperator (Process ID: 999862, Operator ID: 5953ac10-35c0-46d1-97ff-a2c2d53fa02c)
[2021-11-24 15:29:20,287] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - Unique values in seg image: [0 1]
[2021-11-24 15:29:22,188] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - Saving output file ~/src/monai-deploy-app-sdk/notebooks/tutorials/output/dicom_seg-DICOMSEG.dcm
[2021-11-24 15:29:22,346] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - File saved.
Done performing execution of operator DICOMSegmentationWriterOperator
Once the application is verified inside Jupyter notebook, we can write the above Python code into Python files in an application folder.
The application folder structure would look like below:
my_app
├── __main__.py
├── app.py
└── spleen_seg_operator.py
Note
We can create a single application Python file (such as spleen_app.py
) that includes the content of the files, instead of creating multiple files.
You will see such an example in MedNist Classifier Tutorial.
# Create an application folder
!mkdir -p my_app
spleen_seg_operator.py¶
%%writefile my_app/spleen_seg_operator.py
import logging
from os import path
from numpy import uint8
import monai.deploy.core as md
from monai.deploy.core import ExecutionContext, Image, InputContext, IOType, Operator, OutputContext
from monai.deploy.operators.monai_seg_inference_operator import InMemImageReader, MonaiSegInferenceOperator
from monai.transforms import (
Activationsd,
AsDiscreted,
Compose,
CropForegroundd,
EnsureChannelFirstd,
Invertd,
LoadImaged,
SaveImaged,
ScaleIntensityRanged,
Spacingd,
ToTensord,
)
@md.input("image", Image, IOType.IN_MEMORY)
@md.output("seg_image", Image, IOType.IN_MEMORY)
@md.env(pip_packages=["monai>=0.8.1", "torch>=1.5", "numpy>=1.21", "nibabel", "typeguard"])
class SpleenSegOperator(Operator):
"""Performs Spleen segmentation with a 3D image converted from a DICOM CT series.
"""
def __init__(self):
self.logger = logging.getLogger("{}.{}".format(__name__, type(self).__name__))
super().__init__()
self._input_dataset_key = "image"
self._pred_dataset_key = "pred"
def compute(self, op_input: InputContext, op_output: OutputContext, context: ExecutionContext):
input_image = op_input.get("image")
if not input_image:
raise ValueError("Input image is not found.")
output_path = context.output.get().path
# This operator gets an in-memory Image object, so a specialized ImageReader is needed.
_reader = InMemImageReader(input_image)
pre_transforms = self.pre_process(_reader)
post_transforms = self.post_process(pre_transforms, path.join(output_path, "prediction_output"))
# Delegates inference and saving output to the built-in operator.
infer_operator = MonaiSegInferenceOperator(
(
160,
160,
160,
),
pre_transforms,
post_transforms,
)
# Setting the keys used in the dictironary based transforms may change.
infer_operator.input_dataset_key = self._input_dataset_key
infer_operator.pred_dataset_key = self._pred_dataset_key
# Now let the built-in operator handles the work with the I/O spec and execution context.
infer_operator.compute(op_input, op_output, context)
def pre_process(self, img_reader) -> Compose:
"""Composes transforms for preprocessing input before predicting on a model."""
my_key = self._input_dataset_key
return Compose(
[
LoadImaged(keys=my_key, reader=img_reader),
EnsureChannelFirstd(keys=my_key),
Spacingd(keys=my_key, pixdim=[1.0, 1.0, 1.0], mode=["bilinear"], align_corners=True),
ScaleIntensityRanged(keys=my_key, a_min=-57, a_max=164, b_min=0.0, b_max=1.0, clip=True),
CropForegroundd(keys=my_key, source_key=my_key),
ToTensord(keys=my_key),
]
)
def post_process(self, pre_transforms: Compose, out_dir: str = "./prediction_output") -> Compose:
"""Composes transforms for postprocessing the prediction results."""
pred_key = self._pred_dataset_key
return Compose(
[
Activationsd(keys=pred_key, softmax=True),
AsDiscreted(keys=pred_key, argmax=True),
Invertd(
keys=pred_key, transform=pre_transforms, orig_keys=self._input_dataset_key, nearest_interp=True
),
SaveImaged(keys=pred_key, output_dir=out_dir, output_postfix="seg", output_dtype=uint8, resample=False),
]
)
Writing my_app/spleen_seg_operator.py
app.py¶
%%writefile my_app/app.py
import logging
from spleen_seg_operator import SpleenSegOperator
from monai.deploy.core import Application, resource
from monai.deploy.operators.dicom_data_loader_operator import DICOMDataLoaderOperator
from monai.deploy.operators.dicom_seg_writer_operator import DICOMSegmentationWriterOperator
from monai.deploy.operators.dicom_series_selector_operator import DICOMSeriesSelectorOperator
from monai.deploy.operators.dicom_series_to_volume_operator import DICOMSeriesToVolumeOperator
@resource(cpu=1, gpu=1, memory="7Gi")
class AISpleenSegApp(Application):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def compose(self):
study_loader_op = DICOMDataLoaderOperator()
series_selector_op = DICOMSeriesSelectorOperator(Sample_Rules_Text)
series_to_vol_op = DICOMSeriesToVolumeOperator()
# Creates DICOM Seg writer with segment label name in a string list
dicom_seg_writer = DICOMSegmentationWriterOperator(seg_labels=["Spleen"])
# Creates the model specific segmentation operator
spleen_seg_op = SpleenSegOperator()
# Creates the DAG by link the operators
self.add_flow(study_loader_op, series_selector_op, {"dicom_study_list": "dicom_study_list"})
self.add_flow(series_selector_op, series_to_vol_op, {"study_selected_series_list": "study_selected_series_list"})
self.add_flow(series_to_vol_op, spleen_seg_op, {"image": "image"})
self.add_flow(series_selector_op, dicom_seg_writer, {"study_selected_series_list": "study_selected_series_list"})
self.add_flow(spleen_seg_op, dicom_seg_writer, {"seg_image": "seg_image"})
# This is a sample series selection rule in JSON, simply selecting CT series.
# If the study has more than 1 CT series, then all of them will be selected.
# Please see more detail in DICOMSeriesSelectorOperator.
Sample_Rules_Text = """
{
"selections": [
{
"name": "CT Series",
"conditions": {
"StudyDescription": "(.*?)",
"Modality": "(?i)CT",
"SeriesDescription": "(.*?)"
}
}
]
}
"""
if __name__ == "__main__":
# Creates the app and test it standalone. When running is this mode, please note the following:
# -i <DICOM folder>, for input DICOM CT series folder
# -o <output folder>, for the output folder, default $PWD/output
# -m <model file>, for model file path
# e.g.
# python3 app.py -i input -m model.ts
#
AISpleenSegApp(do_run=True)
Writing my_app/app.py
if __name__ == "__main__":
AISpleenSegApp(do_run=True)
The above lines are needed to execute the application code by using python
interpreter.
__main__.py¶
__main__.py is needed for MONAI Application Packager to detect the main application code (app.py
) when the application is executed with the application folder path (e.g., python simple_imaging_app
).
%%writefile my_app/__main__.py
from app import AISpleenSegApp
if __name__ == "__main__":
AISpleenSegApp(do_run=True)
Writing my_app/__main__.py
!ls my_app
app.py __main__.py spleen_seg_operator.py
In this time, let’s execute the app in the command line.
!python my_app -i dcm -o output -m model.ts
Going to initiate execution of operator DICOMDataLoaderOperator
Executing operator DICOMDataLoaderOperator (Process ID: 1000710, Operator ID: f74b2234-c1bc-461a-81b1-4044c3c53d10)
Done performing execution of operator DICOMDataLoaderOperator
Going to initiate execution of operator DICOMSeriesSelectorOperator
Executing operator DICOMSeriesSelectorOperator (Process ID: 1000710, Operator ID: e70b5143-62b8-4bb7-a9a9-87343414189e)
[2021-11-24 15:29:44,079] [INFO] (root) - Finding series for Selection named: CT Series
[2021-11-24 15:29:44,079] [INFO] (root) - Searching study, : 1.2.826.0.1.3680043.2.1125.1.67295333199898911264201812221946213
# of series: 1
[2021-11-24 15:29:44,079] [INFO] (root) - Working on series, instance UID: 1.2.826.0.1.3680043.2.1125.1.68102559796966796813942775094416763
[2021-11-24 15:29:44,079] [INFO] (root) - On attribute: 'StudyDescription' to match value: '(.*?)'
[2021-11-24 15:29:44,079] [INFO] (root) - Series attribute value: spleen
[2021-11-24 15:29:44,080] [INFO] (root) - Series attribute string value did not match. Try regEx.
[2021-11-24 15:29:44,080] [INFO] (root) - On attribute: 'Modality' to match value: '(?i)CT'
[2021-11-24 15:29:44,080] [INFO] (root) - Series attribute value: CT
[2021-11-24 15:29:44,080] [INFO] (root) - Series attribute string value did not match. Try regEx.
[2021-11-24 15:29:44,080] [INFO] (root) - On attribute: 'SeriesDescription' to match value: '(.*?)'
[2021-11-24 15:29:44,080] [INFO] (root) - Series attribute value: No series description
[2021-11-24 15:29:44,080] [INFO] (root) - Series attribute string value did not match. Try regEx.
[2021-11-24 15:29:44,080] [INFO] (root) - Selected Series, UID: 1.2.826.0.1.3680043.2.1125.1.68102559796966796813942775094416763
Done performing execution of operator DICOMSeriesSelectorOperator
Going to initiate execution of operator DICOMSeriesToVolumeOperator
Executing operator DICOMSeriesToVolumeOperator (Process ID: 1000710, Operator ID: 3ef89a0a-07d4-41e8-9744-c4b7e4020ae6)
Done performing execution of operator DICOMSeriesToVolumeOperator
Going to initiate execution of operator SpleenSegOperator
Executing operator SpleenSegOperator (Process ID: 1000710, Operator ID: 1493e6ee-9391-4c76-a721-6b8d46f6e253)
Converted Image object metadata:
SeriesInstanceUID: 1.2.826.0.1.3680043.2.1125.1.68102559796966796813942775094416763, type <class 'str'>
Modality: CT, type <class 'str'>
SeriesDescription: No series description, type <class 'str'>
PatientPosition: HFS, type <class 'str'>
SeriesNumber: 1, type <class 'int'>
row_pixel_spacing: 1.0, type <class 'float'>
col_pixel_spacing: 1.0, type <class 'float'>
depth_pixel_spacing: 1.0, type <class 'float'>
row_direction_cosine: [-1.0, 0.0, 0.0], type <class 'list'>
col_direction_cosine: [0.0, -1.0, 0.0], type <class 'list'>
depth_direction_cosine: [0.0, 0.0, 1.0], type <class 'list'>
dicom_affine_transform: [[-1. 0. 0. 0.]
[ 0. -1. 0. 0.]
[ 0. 0. 1. 0.]
[ 0. 0. 0. 1.]], type <class 'numpy.ndarray'>
nifti_affine_transform: [[ 1. -0. -0. -0.]
[-0. 1. -0. -0.]
[ 0. 0. 1. 0.]
[ 0. 0. 0. 1.]], type <class 'numpy.ndarray'>
StudyInstanceUID: 1.2.826.0.1.3680043.2.1125.1.67295333199898911264201812221946213, type <class 'str'>
StudyID: SLICER10001, type <class 'str'>
StudyDate: 2019-09-16, type <class 'str'>
StudyTime: 010100.000000, type <class 'str'>
StudyDescription: spleen, type <class 'str'>
AccessionNumber: 1, type <class 'str'>
selection_name: CT Series, type <class 'str'>
file written: ~/src/monai-deploy-app-sdk/notebooks/tutorials/output/prediction_output/1.2.826.0.1.3680043.2.1125.1/1.2.826.0.1.3680043.2.1125.1_seg.nii.gz.
Output Seg image numpy array shaped: (515, 440, 440)
Output Seg image pixel max value: 1
Done performing execution of operator SpleenSegOperator
Going to initiate execution of operator DICOMSegmentationWriterOperator
Executing operator DICOMSegmentationWriterOperator (Process ID: 1000710, Operator ID: 61e30bdb-2d21-4fad-9a06-ad17c6f308df)
[2021-11-24 15:29:55,905] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - Number of DICOM instance datasets in the list: 515
[2021-11-24 15:29:55,905] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - Number of slices in the numpy image: 515
[2021-11-24 15:29:55,905] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - Labels of the segments: ['Spleen']
[2021-11-24 15:29:57,442] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - Unique values in seg image: [0 1]
[2021-11-24 15:29:59,170] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - Saving output file ~/src/monai-deploy-app-sdk/notebooks/tutorials/output/dicom_seg-DICOMSEG.dcm
[2021-11-24 15:29:59,323] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - File saved.
Done performing execution of operator DICOMSegmentationWriterOperator
Above command is same with the following command line:
import os
os.environ['MKL_THREADING_LAYER'] = 'GNU'
!monai-deploy exec my_app -i dcm -o output -m model.ts
Going to initiate execution of operator DICOMDataLoaderOperator
Executing operator DICOMDataLoaderOperator (Process ID: 1002078, Operator ID: a41f4089-5f8f-4ef2-b8d8-b4224c9518e9)
Done performing execution of operator DICOMDataLoaderOperator
Going to initiate execution of operator DICOMSeriesSelectorOperator
Executing operator DICOMSeriesSelectorOperator (Process ID: 1002078, Operator ID: fc706328-9c42-4ff6-842f-221092170a9a)
[2021-11-24 15:31:24,236] [INFO] (root) - Finding series for Selection named: CT Series
[2021-11-24 15:31:24,236] [INFO] (root) - Searching study, : 1.2.826.0.1.3680043.2.1125.1.67295333199898911264201812221946213
# of series: 1
[2021-11-24 15:31:24,236] [INFO] (root) - Working on series, instance UID: 1.2.826.0.1.3680043.2.1125.1.68102559796966796813942775094416763
[2021-11-24 15:31:24,236] [INFO] (root) - On attribute: 'StudyDescription' to match value: '(.*?)'
[2021-11-24 15:31:24,236] [INFO] (root) - Series attribute value: spleen
[2021-11-24 15:31:24,236] [INFO] (root) - Series attribute string value did not match. Try regEx.
[2021-11-24 15:31:24,236] [INFO] (root) - On attribute: 'Modality' to match value: '(?i)CT'
[2021-11-24 15:31:24,236] [INFO] (root) - Series attribute value: CT
[2021-11-24 15:31:24,236] [INFO] (root) - Series attribute string value did not match. Try regEx.
[2021-11-24 15:31:24,236] [INFO] (root) - On attribute: 'SeriesDescription' to match value: '(.*?)'
[2021-11-24 15:31:24,236] [INFO] (root) - Series attribute value: No series description
[2021-11-24 15:31:24,236] [INFO] (root) - Series attribute string value did not match. Try regEx.
[2021-11-24 15:31:24,236] [INFO] (root) - Selected Series, UID: 1.2.826.0.1.3680043.2.1125.1.68102559796966796813942775094416763
Done performing execution of operator DICOMSeriesSelectorOperator
Going to initiate execution of operator DICOMSeriesToVolumeOperator
Executing operator DICOMSeriesToVolumeOperator (Process ID: 1002078, Operator ID: 3ca4482b-2cc2-4309-ad80-a896b3ea7a82)
Done performing execution of operator DICOMSeriesToVolumeOperator
Going to initiate execution of operator SpleenSegOperator
Executing operator SpleenSegOperator (Process ID: 1002078, Operator ID: 7837e92c-5ecf-4a0c-a19d-53a1786d546b)
Converted Image object metadata:
SeriesInstanceUID: 1.2.826.0.1.3680043.2.1125.1.68102559796966796813942775094416763, type <class 'str'>
Modality: CT, type <class 'str'>
SeriesDescription: No series description, type <class 'str'>
PatientPosition: HFS, type <class 'str'>
SeriesNumber: 1, type <class 'int'>
row_pixel_spacing: 1.0, type <class 'float'>
col_pixel_spacing: 1.0, type <class 'float'>
depth_pixel_spacing: 1.0, type <class 'float'>
row_direction_cosine: [-1.0, 0.0, 0.0], type <class 'list'>
col_direction_cosine: [0.0, -1.0, 0.0], type <class 'list'>
depth_direction_cosine: [0.0, 0.0, 1.0], type <class 'list'>
dicom_affine_transform: [[-1. 0. 0. 0.]
[ 0. -1. 0. 0.]
[ 0. 0. 1. 0.]
[ 0. 0. 0. 1.]], type <class 'numpy.ndarray'>
nifti_affine_transform: [[ 1. -0. -0. -0.]
[-0. 1. -0. -0.]
[ 0. 0. 1. 0.]
[ 0. 0. 0. 1.]], type <class 'numpy.ndarray'>
StudyInstanceUID: 1.2.826.0.1.3680043.2.1125.1.67295333199898911264201812221946213, type <class 'str'>
StudyID: SLICER10001, type <class 'str'>
StudyDate: 2019-09-16, type <class 'str'>
StudyTime: 010100.000000, type <class 'str'>
StudyDescription: spleen, type <class 'str'>
AccessionNumber: 1, type <class 'str'>
selection_name: CT Series, type <class 'str'>
file written: ~/src/monai-deploy-app-sdk/notebooks/tutorials/output/prediction_output/1.2.826.0.1.3680043.2.1125.1/1.2.826.0.1.3680043.2.1125.1_seg.nii.gz.
Output Seg image numpy array shaped: (515, 440, 440)
Output Seg image pixel max value: 1
Done performing execution of operator SpleenSegOperator
Going to initiate execution of operator DICOMSegmentationWriterOperator
Executing operator DICOMSegmentationWriterOperator (Process ID: 1002078, Operator ID: 94777d8c-a82e-42c3-99f5-ac7fdb0dc4dd)
[2021-11-24 15:31:34,476] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - Number of DICOM instance datasets in the list: 515
[2021-11-24 15:31:34,476] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - Number of slices in the numpy image: 515
[2021-11-24 15:31:34,476] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - Labels of the segments: ['Spleen']
[2021-11-24 15:31:36,032] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - Unique values in seg image: [0 1]
[2021-11-24 15:31:37,810] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - Saving output file ~/src/monai-deploy-app-sdk/notebooks/tutorials/output/dicom_seg-DICOMSEG.dcm
[2021-11-24 15:31:37,964] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - File saved.
Done performing execution of operator DICOMSegmentationWriterOperator
!ls output
dicom_seg-DICOMSEG.dcm prediction_output
Packaging app¶
Let’s package the app with MONAI Application Packager.
!monai-deploy package -b nvcr.io/nvidia/pytorch:21.11-py3 my_app --tag my_app:latest -m model.ts
Building MONAI Application Package... Done
[2021-11-24 16:01:18,268] [INFO] (app_packager) - Successfully built my_app:latest
Note
Building a MONAI Application Package (Docker image) can take time. Use -l DEBUG
option if you want to see the progress.
We can see that the Docker image is created.
!docker image ls | grep my_app
my_app latest 4f5025774c06 6 seconds ago 14.9GB
Executing packaged app locally¶
The packaged app can be run locally through MONAI Application Runner.
# Copy DICOM files are in 'dcm' folder
# Launch the app
!monai-deploy run my_app:latest dcm output
Checking dependencies...
--> Verifying if "docker" is installed...
--> Verifying if "my_app:latest" is available...
Checking for MAP "my_app:latest" locally
"my_app:latest" found.
Reading MONAI App Package manifest...
--> Verifying if "nvidia-docker" is installed...
Going to initiate execution of operator DICOMDataLoaderOperator
Executing operator DICOMDataLoaderOperator (Process ID: 1, Operator ID: 441a7274-a2dd-4b01-99c4-170b51c248d7)
Done performing execution of operator DICOMDataLoaderOperator
Going to initiate execution of operator DICOMSeriesSelectorOperator
Executing operator DICOMSeriesSelectorOperator (Process ID: 1, Operator ID: e5f2533b-cc73-4c7f-9e57-84dca9380776)
[2021-11-24 21:01:34,900] [INFO] (root) - Finding series for Selection named: CT Series
[2021-11-24 21:01:34,900] [INFO] (root) - Searching study, : 1.2.826.0.1.3680043.2.1125.1.67295333199898911264201812221946213
# of series: 1
[2021-11-24 21:01:34,900] [INFO] (root) - Working on series, instance UID: 1.2.826.0.1.3680043.2.1125.1.68102559796966796813942775094416763
[2021-11-24 21:01:34,901] [INFO] (root) - On attribute: 'StudyDescription' to match value: '(.*?)'
[2021-11-24 21:01:34,901] [INFO] (root) - Series attribute value: spleen
[2021-11-24 21:01:34,901] [INFO] (root) - Series attribute string value did not match. Try regEx.
[2021-11-24 21:01:34,901] [INFO] (root) - On attribute: 'Modality' to match value: '(?i)CT'
[2021-11-24 21:01:34,901] [INFO] (root) - Series attribute value: CT
[2021-11-24 21:01:34,901] [INFO] (root) - Series attribute string value did not match. Try regEx.
[2021-11-24 21:01:34,901] [INFO] (root) - On attribute: 'SeriesDescription' to match value: '(.*?)'
[2021-11-24 21:01:34,901] [INFO] (root) - Series attribute value: No series description
[2021-11-24 21:01:34,901] [INFO] (root) - Series attribute string value did not match. Try regEx.
[2021-11-24 21:01:34,901] [INFO] (root) - Selected Series, UID: 1.2.826.0.1.3680043.2.1125.1.68102559796966796813942775094416763
Done performing execution of operator DICOMSeriesSelectorOperator
Going to initiate execution of operator DICOMSeriesToVolumeOperator
Executing operator DICOMSeriesToVolumeOperator (Process ID: 1, Operator ID: 0cb153e2-f98d-432a-b953-4b9238821062)
Done performing execution of operator DICOMSeriesToVolumeOperator
Going to initiate execution of operator SpleenSegOperator
Executing operator SpleenSegOperator (Process ID: 1, Operator ID: fad57270-f46f-46ff-a5c0-88723f1fb717)
Converted Image object metadata:
SeriesInstanceUID: 1.2.826.0.1.3680043.2.1125.1.68102559796966796813942775094416763, type <class 'str'>
Modality: CT, type <class 'str'>
SeriesDescription: No series description, type <class 'str'>
PatientPosition: HFS, type <class 'str'>
SeriesNumber: 1, type <class 'int'>
row_pixel_spacing: 1.0, type <class 'float'>
col_pixel_spacing: 1.0, type <class 'float'>
depth_pixel_spacing: 1.0, type <class 'float'>
row_direction_cosine: [-1.0, 0.0, 0.0], type <class 'list'>
col_direction_cosine: [0.0, -1.0, 0.0], type <class 'list'>
depth_direction_cosine: [0.0, 0.0, 1.0], type <class 'list'>
dicom_affine_transform: [[-1. 0. 0. 0.]
[ 0. -1. 0. 0.]
[ 0. 0. 1. 0.]
[ 0. 0. 0. 1.]], type <class 'numpy.ndarray'>
nifti_affine_transform: [[ 1. -0. -0. -0.]
[-0. 1. -0. -0.]
[ 0. 0. 1. 0.]
[ 0. 0. 0. 1.]], type <class 'numpy.ndarray'>
StudyInstanceUID: 1.2.826.0.1.3680043.2.1125.1.67295333199898911264201812221946213, type <class 'str'>
StudyID: SLICER10001, type <class 'str'>
StudyDate: 2019-09-16, type <class 'str'>
StudyTime: 010100.000000, type <class 'str'>
StudyDescription: spleen, type <class 'str'>
AccessionNumber: 1, type <class 'str'>
selection_name: CT Series, type <class 'str'>
file written: /var/monai/output/prediction_output/1.2.826.0.1.3680043.2.1125.1/1.2.826.0.1.3680043.2.1125.1_seg.nii.gz.
Output Seg image numpy array shaped: (515, 440, 440)
Output Seg image pixel max value: 1
Done performing execution of operator SpleenSegOperator
Going to initiate execution of operator DICOMSegmentationWriterOperator
Executing operator DICOMSegmentationWriterOperator (Process ID: 1, Operator ID: 90f5b1e4-71c0-48a1-91d9-f1d462683c14)
[2021-11-24 21:01:48,195] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - Number of DICOM instance datasets in the list: 515
[2021-11-24 21:01:48,195] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - Number of slices in the numpy image: 515
[2021-11-24 21:01:48,195] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - Labels of the segments: ['Spleen']
[2021-11-24 21:01:49,743] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - Unique values in seg image: [0 1]
[2021-11-24 21:01:51,712] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - Saving output file /var/monai/output/dicom_seg-DICOMSEG.dcm
[2021-11-24 21:01:51,874] [INFO] (monai.deploy.operators.dicom_seg_writer_operator.DICOMSegWriter) - File saved.
Done performing execution of operator DICOMSegmentationWriterOperator
!ls output
dicom_seg-DICOMSEG.dcm prediction_output