Image with defective pixels while export in different image formats(.png, .tiff)

Good day, while i try to export single image from .nii file in result i get an image but with defective pixels. I also tried to cast image from sitkUInt8 to sitkUInt16 but it become worse.

import sys
import SimpleITK as sitk

if len(sys.argv) is 3:
    inputImageName = sys.argv[1]
    output = sys.argv[2]

    reader = sitk.ReadImage(inputImageName)
    image = reader[256, :, :]
    filePath = output + "/image.tiff"
    image = sitk.Cast(image, sitk.sitkUInt8)

    sitk.WriteImage(image, filePath)    
    print("Not enough arguments!")

image.tiff (206.2 KB)
image.tiff (412.2 KB)

But if i open same .nii for example in Slicer3D it looks:

I can’t figure out what I’m doing wrong.

Your input image is probably 16 bit. Certainly more than 8 bit. So when you are casting it to an 8 bit unsigned int, the pixel values are overflowing. If you really want 8-bit pixels, you’re going to have to re-map the intensities to the 0-255 range.

Hello @rubellion,

Welcome to SimpleITK!

What you are seeing is overflow. The Cast operation does a simple cast between data types and that is not what you want. The original CT image has a high dynamic range, intensity values in Hounsfield Units outside the [0,255] range. Simple solution:

image = sitk.Cast(sitk.RescaleIntensity(image), sitk.sitkUInt8)

A solution with more fine grained control over mapping the intensities is provided by the IntensityWindowingImageFilter. As the example was showing a sagittal view, you will also need to make the image isotropic (see discussion and make_isotropic function in this Jupyter notebook).

Hello, @dchen and @zivy. Thank you for replies! Problem is resolved! Good day.