2
votes

I need to make a conversion from a DICOM image to a JPG/PNG and save the image using VTK, but the image that I produce does not match the original.

enter image description here

I know I need rescaling the pixels of the image to convert it but I do not know how. Does anyone know how I can do the conversion properly?

Below, my code in python:

from vtk import *

reader = vtkDICOMImageReader()
reader.SetFileName('image.dcm')
reader.Update()

castFilter = vtkImageCast()
castFilter.SetOutputScalarTypeToUnsignedChar()
castFilter.SetInputConnection(reader.GetOutputPort())
castFilter.Update()

writer = vtkJPEGWriter()
writer.SetFileName('output.jpg')
writer.SetInputConnection(castFilter.GetOutputPort())
writer.Write()
2

2 Answers

3
votes

DICOMs in MRI and CT modalities are generally short types, and you are casting the image to unsigned char mercilessly. If you are trying to get a corresponding uchar image, you should be using vtkImageShiftScale, just like the vtkImageCast docs say:

Warning As vtkImageCast only casts values without rescaling them, its use is not recommented. vtkImageShiftScale is the recommented way to change the type of an image data.

2
votes

I made the conversion, here is my code:

from vtk import vtkDICOMImageReader
from vtk import vtkImageShiftScale
from vtk import vtkPNGWriter

reader = vtkDICOMImageReader()
reader.SetFileName('image.dcm')
reader.Update()
image = reader.GetOutput()

shiftScaleFilter = vtkImageShiftScale()
shiftScaleFilter.SetOutputScalarTypeToUnsignedChar()
shiftScaleFilter.SetInputConnection(reader.GetOutputPort())

shiftScaleFilter.SetShift(-1.0*image.GetScalarRange()[0])
oldRange = image.GetScalarRange()[1] - image.GetScalarRange()[0]
newRange = 255

shiftScaleFilter.SetScale(newRange/oldRange)
shiftScaleFilter.Update()

writer = vtkPNGWriter()
writer.SetFileName('output.jpg')
writer.SetInputConnection(shiftScaleFilter.GetOutputPort())
writer.Write()