Convert nifti segmentation mask to DICOM RTstruct

I have segmented some brain areas and have the results as a binary mask in a nifti file. I now need to convert the nifti file into a DICOM RTstruct file, which stores contours (coordinates) for each slice in the volume. I can get the coordinates using a function in scikit-image, but it is not clear how to save them into a DICOM RTstruct file. I have found tools for dcmtrstuct2nii but not the opposite. Has anyone done this before?

I would suggest you try 3D Slicer. I have posted a question on their forum, but you may want to write your own specific question on their forum if you have issues.

I need to run it inside a Docker container, so I ended up making my own Python script

Hey, though it seems like you’ve already solved this, A team and I actually wrote a small Python package called RT-Utils that deals with this exactly! You can find the package here for better documentation and you can install the package via pip.

For your use case, it should be as easy as the code below. Note however that RTUtils works with numpy arrays so you would need to convert your nifti data to numpy first:

from rt_utils import RTStructBuilder

# Create new RT Struct. Requires the DICOM series path for the RT Struct.
rtstruct = RTStructBuilder.create_new(dicom_series_path="./testlocation")

# Your code to generate the segmentation mask
nifti_segmentation_mask = get_your_segmentation_mask_somehow()
numpy_segmentation_mask = convert_nifti_to_numpy_ndarray(nifti_segmentation_mask )

# Add the 3D mask as an ROI.
rtstruct.add_roi(mask=numpy_segmentation_mask)

# Save the resulting RT Struct
rtstruct.save('new-rt-struct')

For further info, check out this blogpost.