Search code examples
python-2.7vtkdicom

Convert DICOM image using VTK


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()

Solution

  • 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()