Example: python

This page shows a simple example on how to containerize your python script for this challenge. The source code can also be found on github: hjkuijf/MRBrainS18.

The following python script simply thresholds the pre/reg_T1 image at various gray levels. It uses SimpleITK to load/save the images, and numpy to perform the thresholding.

import numpy as np
import os
import SimpleITK as sitk

inputDir = '/input'
outputDir = '/output'

# Load the image
t1Image = sitk.ReadImage(os.path.join(inputDir, 'pre', 'reg_T1.nii.gz'))
t1Array = sitk.GetArrayFromImage(t1Image)

# Apply some simple thresholds
t1Array[t1Array < 10] = 0 # Background t1Array[(t1Array >=  10) & (t1Array < 80)] = 5 # CSF t1Array[(t1Array >=  80) & (t1Array < 130)] = 1 # cGM t1Array[(t1Array >= 130) & (t1Array < 150)] = 2 # BG t1Array[(t1Array >= 150)] = 3                   # WM

resultImage = sitk.GetImageFromArray(t1Array)
resultImage.CopyInformation(t1Image)

sitk.WriteImage(resultImage, os.path.join(outputDir, 'result.nii.gz'))

This code needs a basic Python installation, with numpy and SimpleITK added. We therefore used miniconda, which has Docker container available that we can inherit from: continuumio/miniconda.

Our example Dockerfile looks like this:

FROM continuumio/miniconda
MAINTAINER hjkuijf

RUN pip install numpy SimpleITK

ADD python /mrbrains18_example

Our Python code is saved next to this Dockerfile in the folder python/example.py. With the following command, we build a Docker container from our Dockerfile and the Python source code:

docker build -f Dockerfile -t mrbrains18/[TEAM-NAME] .

Note: the . at the end specifies that everything is in the current folder. Hence, you run this build command from the folder that contains the Dockerfile and the source code.

Once your container is ready, we can run it with the following command:

docker run --network none -dit -v [TEST-ORIG]:/input/orig:ro -v [TEST-PRE]:/input/pre:ro -v /output mrbrains18/[TEAM-NAME]

The first two -v options map the input folder into the container at /input, read-only. The last -v creates a temporary output directory.

This command outputs the Container ID, which you can also look up with:

docker ps

Next, we will execute the example Python script:

docker exec [CONTAINER-ID] python /mrbrains18_example/example.py

Since this script is quite small, it doesn’t take long to finish. Next we copy the output from the container to our local machine:

docker cp [CONTAINER-ID]:/output [RESULT-LOCATION]

Finally, we shut down the running container. This also removes the temporary /output folder and any other changes made to the container.

docker rm -v [CONTAINER-ID]