Last active
February 3, 2018 17:59
-
-
Save samuelhei/6d213a37eca1afaeb732c270c4bd49d7 to your computer and use it in GitHub Desktop.
Dicom to PNG setting window and level. Modified from: http://vtk.1045678.n5.nabble.com/Set-window-level-and-convert-image-DICOM-tp5736087p5736157.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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