Skip to content

Instantly share code, notes, and snippets.

@samuelhei
Last active February 3, 2018 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samuelhei/6d213a37eca1afaeb732c270c4bd49d7 to your computer and use it in GitHub Desktop.
Save samuelhei/6d213a37eca1afaeb732c270c4bd49d7 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import sys, getopt
from vtk import *
def main(argv):
inputfile = ''
outputfile = ''
window = 80
level = 40
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print '__main__.py -i <inputfile> -o <outputfile>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print('test.py -i <inputfile> -o <outputfile>')
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print 'Generating ', inputfile
generateImg(inputfile, outputfile, window, level)
def generateImg(inputfile, outputfile, window, level):
reader = vtkDICOMImageReader()
reader.SetFileName(inputfile)
reader.Update()
image = reader.GetOutput()
windowlevel = vtkImageMapToWindowLevelColors()
windowlevel.SetInput(reader.GetOutput())
windowlevel.SetWindow(window)
windowlevel.SetLevel(level)
windowlevel.Update()
shiftScaleFilter = vtkImageShiftScale()
shiftScaleFilter.SetOutputScalarTypeToUnsignedChar()
shiftScaleFilter.SetInputConnection(windowlevel.GetOutputPort())
shiftScaleFilter.SetShift(-1.0*windowlevel.GetOutput().GetScalarRange()[0])
oldRange = windowlevel.GetOutput().GetScalarRange()[1] - windowlevel.GetOutput().GetScalarRange()[0]
newRange = 255
shiftScaleFilter.SetScale(newRange/oldRange)
shiftScaleFilter.Update()
writer = vtkPNGWriter()
writer.SetFileName(outputfile)
writer.SetInputConnection(windowlevel.GetOutputPort())
writer.Write()
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment