pythonmasksimpleitknifti

Merge channels of NIfTI (.nii) images in python


I am trying to superimpose a CT .nii image and its mask in another color (possibly red). This is easily achievable for example with imageJ, thanks to the "Merge Channels" functionality. What I would like to obtain looks like this:

this

given my original image:

original image

and its mask:

its mask

So basically I need to "convert to red" my mask and superimpose it on my grayscale image.

I've looked into SimpleITK (this is how I made the contour mask) but I can't proceed forward from here. Can anyone help?


Solution

  • Here's a SimpleITK script that overlays a mask on an image:

    import SimpleITK as sitk
    
    img = sitk.ReadImage("ct.jpg")
    mask = sitk.ReadImage("mask.png")
    
    # Extract one channel since the images are actually RGB
    img = sitk.VectorIndexSelectionCast(img, 0)
    mask = sitk.VectorIndexSelectionCast(mask, 0)
    
    mask = mask>200
    
    red = [255, 0, 0]
    
    color_overlay = sitk.LabelMapOverlay( sitk.Cast(mask, sitk.sitkLabelUInt8),
        img, opacity=0.5, colormap=red )
    
    sitk.WriteImage(color_overlay, "overlay.png")
    

    And here's resulting output image: enter image description here

    Note that the script first extracts one channel from image and mask to create grayscale images (since your examples were RGB). Also, it does a threshold on the mask to create a binary mask (0s and 1s).