Пример #1
0
def ProcessOneFilePublic(filename, outfilename, tmpfile):
    gdcm.ImageHelper.SetForceRescaleInterceptSlope(True)
    vtkreader = vtkgdcm.vtkGDCMImageReader()
    vtkreader.SetFileName(filename)
    vtkreader.Update()

    cast = vtk.vtkImageCast()
    cast.SetInput(vtkreader.GetOutput())
    cast.SetOutputScalarTypeToUnsignedShort()

    # vtkGDCMImageWriter does not support Sequence, so let's write a tmp file first:
    # Some operation will actually be discarded (we simply need a temp storage)
    vtkwriter = vtkgdcm.vtkGDCMImageWriter()
    vtkwriter.SetFileName(tmpfile)
    vtkwriter.SetMedicalImageProperties(vtkreader.GetMedicalImageProperties())
    vtkwriter.SetDirectionCosines(vtkreader.GetDirectionCosines())
    print "Format:", vtkreader.GetImageFormat()
    vtkwriter.SetImageFormat(vtkreader.GetImageFormat())
    vtkwriter.SetInput(cast.GetOutput())
    #vtkwriter.Update()
    vtkwriter.Write()

    # ok now rewrite the exact same file as the original (keep all info)
    # but use the Pixel Data Element from the written file
    tmpreader = gdcm.ImageReader()
    tmpreader.SetFileName(tmpfile)
    if not tmpreader.Read():
        sys.exit(1)

    reader = gdcm.Reader()
    reader.SetFileName(filename)
    if not reader.Read():
        sys.exit(1)

    # Make sure to remove Slope/Rescale to avoid re-execution
    ds = reader.GetFile().GetDataSet()
    tags = [
        gdcm.Tag(0x0028, 0x1052),
        gdcm.Tag(0x0028, 0x1053),
        gdcm.Tag(0x0028, 0x1053),
    ]
    for tag in tags:
        ds.Remove(tag)

    writer = gdcm.ImageWriter()
    writer.SetFileName(outfilename)
    # Pass image from vtk written file
    writer.SetImage(tmpreader.GetImage())
    # pass dataset from initial 'reader'
    writer.SetFile(reader.GetFile())
    if not writer.Write():
        sys.exit(1)
Пример #2
0
def ProcessOneFilePublic(filename, outfilename, tmpfile):
  gdcm.ImageHelper.SetForceRescaleInterceptSlope(True)
  vtkreader = vtkgdcm.vtkGDCMImageReader()
  vtkreader.SetFileName( filename )
  vtkreader.Update()

  cast = vtk.vtkImageCast()
  cast.SetInput( vtkreader.GetOutput() )
  cast.SetOutputScalarTypeToUnsignedShort()

  # vtkGDCMImageWriter does not support Sequence, so let's write a tmp file first:
  # Some operation will actually be discarded (we simply need a temp storage)
  vtkwriter = vtkgdcm.vtkGDCMImageWriter()
  vtkwriter.SetFileName( tmpfile )
  vtkwriter.SetMedicalImageProperties( vtkreader.GetMedicalImageProperties() )
  vtkwriter.SetDirectionCosines( vtkreader.GetDirectionCosines() )
  print "Format:",vtkreader.GetImageFormat()
  vtkwriter.SetImageFormat( vtkreader.GetImageFormat() )
  vtkwriter.SetInput( cast.GetOutput() )
  #vtkwriter.Update()
  vtkwriter.Write()
  
  # ok now rewrite the exact same file as the original (keep all info)
  # but use the Pixel Data Element from the written file
  tmpreader = gdcm.ImageReader()
  tmpreader.SetFileName( tmpfile )
  if not tmpreader.Read():
    sys.exit(1)

  reader = gdcm.Reader()
  reader.SetFileName( filename )
  if not reader.Read():
    sys.exit(1)

  # Make sure to remove Slope/Rescale to avoid re-execution
  ds = reader.GetFile().GetDataSet()
  tags = [
    gdcm.Tag(0x0028,0x1052),
    gdcm.Tag(0x0028,0x1053),
    gdcm.Tag(0x0028,0x1053),
  ]
  for tag in tags:
    ds.Remove( tag )

  writer = gdcm.ImageWriter()
  writer.SetFileName( outfilename )
  # Pass image from vtk written file
  writer.SetImage( tmpreader.GetImage() )
  # pass dataset from initial 'reader'
  writer.SetFile( reader.GetFile() )
  if not writer.Write():
    sys.exit(1)
Пример #3
0
    def __init__(self, module_manager):
        ModuleBase.__init__(self, module_manager)

        self._writer = vtkgdcm.vtkGDCMImageWriter()
        # NB NB NB: for now we're SWITCHING off the VTK-compatible
        # Y-flip, until the X-mirror issues can be solved.
        self._writer.SetFileLowerLeft(1)
        module_utils.setup_vtk_object_progress(self, self._writer,
                                           'Writing DICOM data')

        self._caster = vtk.vtkImageCast()
        self._caster.SetOutputScalarTypeToShort()
        module_utils.setup_vtk_object_progress(self, self._caster,
                'Casting DICOM data to short')

        self._input_data = None
        self._input_metadata = None

        self._config.output_mode = 0
        self._config.output_directory = ''
        self._config.output_filename = ''
        self._config.cast_to_short = True

        config_list = [
                ('Output mode:', 'output_mode', 'base:int',
                    'radiobox', 'Output mode',
                    ['Slice-per-file (directory)', 
                     'Multi-slice per file (file)']),
                ('Output directory:', 'output_directory', 'base:str',
                'dirbrowser', 
                'Directory that takes slice-per-file output'),
                ('Output filename:', 'output_filename', 'base:str',
                 'filebrowser', 
                 'Output filename for multi-slice per file output.',
                 {'fileMode' : wx.SAVE,
                     'fileMask' : 'DICOM file (*.dcm)|*.dcm|'
                     'All files (*.*)|*.*'}
                 ),
                ('Cast to short:', 'cast_to_short', 'base:bool',
                    'checkbox',
                    'Should the data be cast to signed 16-bit (short), '
                    'common for DICOM.')
                ]

        ScriptedConfigModuleMixin.__init__(self, config_list,
                {'Module (self)' : self})


        self.sync_module_logic_with_config()
Пример #4
0
    def __init__(self, module_manager):
        ModuleBase.__init__(self, module_manager)

        self._writer = vtkgdcm.vtkGDCMImageWriter()
        # NB NB NB: for now we're SWITCHING off the VTK-compatible
        # Y-flip, until the X-mirror issues can be solved.
        self._writer.SetFileLowerLeft(1)
        module_utils.setup_vtk_object_progress(self, self._writer,
                                               'Writing DICOM data')

        self._caster = vtk.vtkImageCast()
        self._caster.SetOutputScalarTypeToShort()
        module_utils.setup_vtk_object_progress(self, self._caster,
                                               'Casting DICOM data to short')

        self._input_data = None
        self._input_metadata = None

        self._config.output_mode = 0
        self._config.output_directory = ''
        self._config.output_filename = ''
        self._config.cast_to_short = True

        config_list = [
            ('Output mode:', 'output_mode', 'base:int', 'radiobox',
             'Output mode',
             ['Slice-per-file (directory)', 'Multi-slice per file (file)']),
            ('Output directory:', 'output_directory', 'base:str', 'dirbrowser',
             'Directory that takes slice-per-file output'),
            ('Output filename:', 'output_filename', 'base:str', 'filebrowser',
             'Output filename for multi-slice per file output.', {
                 'fileMode': wx.SAVE,
                 'fileMask': 'DICOM file (*.dcm)|*.dcm|'
                 'All files (*.*)|*.*'
             }),
            ('Cast to short:', 'cast_to_short', 'base:bool', 'checkbox',
             'Should the data be cast to signed 16-bit (short), '
             'common for DICOM.')
        ]

        ScriptedConfigModuleMixin.__init__(self, config_list,
                                           {'Module (self)': self})

        self.sync_module_logic_with_config()
Пример #5
0
def PrintProgress(object, event):
    assert event == "ProgressEvent"
    print("Progress:", object.GetProgress())


if __name__ == "__main__":
    try:
        filename = os.sys.argv[1]
    except:
        # failure
        print("Need a filename")
        sys.exit(1)

    # setup reader
    r = vtkgdcm.vtkGDCMImageReader()

    r.SetFileName(filename)
    r.AddObserver("ProgressEvent", PrintProgress)
    r.Update()
    print(r.GetOutput())
    # Write output
    writer = vtkgdcm.vtkGDCMImageWriter()
    writer.SetInput(r.GetOutput())
    writer.SetMedicalImageProperties(r.GetMedicalImageProperties())
    writer.SetFileName("TestvtkGDCMImageWriterPython.dcm")
    writer.Write()

    # Test succeed ?
    #sys.exit(sucess != 1)
def PrintProgress(object, event):
  assert event == "ProgressEvent"
  print "Progress:", object.GetProgress()

if __name__ == "__main__":
  try:
    filename = os.sys.argv[1]
  except:
    # failure
    print "Need a filename"
    sys.exit(1)
  
  # setup reader
  r = vtkgdcm.vtkGDCMImageReader()
  
  r.SetFileName( filename )
  r.AddObserver("ProgressEvent", PrintProgress)
  r.Update()
  print r.GetOutput()
  # Write output
  writer = vtkgdcm.vtkGDCMImageWriter()
  writer.SetInput( r.GetOutput() )
  writer.SetMedicalImageProperties( r.GetMedicalImageProperties() )
  writer.SetFileName( "TestvtkGDCMImageWriterPython.dcm" )
  writer.Write()
  
  # Test succeed ?
  #sys.exit(sucess != 1)

Пример #7
0
VTK_DATA_ROOT = vtkGetDataRoot()

r = vtkgdcm.vtkGDCMImageReader()
r.SetFileName( VTK_DATA_ROOT + "/Data/mr.001" )
r.Update()

#print r.GetOutput()

# Pixel Spacing
# 0.78125, 0.78125, 0

# Image Position (Patient)
# -13.3034, -80.8219, 119.178

# try to rewrite it:
w = vtkgdcm.vtkGDCMImageWriter()
w.SetInput( r.GetOutput() )
w.SetMedicalImageProperties( r.GetMedicalImageProperties() )
w.SetDirectionCosines( r.GetDirectionCosines() )
w.SetFileName( "mr.001.dcm" )
w.Write()

# beach.tif
#tiffreader = vtk.vtkTIFFReader()
#tiffreader.SetFileName( VTK_DATA_ROOT + "/Data/beach.tif" )
#tiffreader.Update()
# print tiffreader.GetOutput()
# -> TIFF reader was apparently broken in VTK until some very recent
# version and thus image appear upside down, unless you also update VTKData :(

jpegreader = vtk.vtkJPEGReader()
Пример #8
0
def ProcessOneFilePrivate(filename, outfilename, tmpfile):
  vtkreader = vtkgdcm.vtkGDCMImageReader()
  vtkreader.SetFileName( filename )
  vtkreader.Update()
  
  
  # (2005,1409)     DS      4       0.0
  # (2005,140a)     DS      16      1.52283272283272
  
  # (2005,0014)     LO      26      Philips MR Imaging DD 005
  tag1 = gdcm.PrivateTag(0x2005,0x09,"Philips MR Imaging DD 005")
  tag2 = gdcm.PrivateTag(0x2005,0x0a,"Philips MR Imaging DD 005")
  
  
  
  # Need to access some private tags, reread the file (for now):
  reader = gdcm.Reader()
  reader.SetFileName( filename )
  if not reader.Read():
    sys.exit(1)
  
  ds = reader.GetFile().GetDataSet()
  
  el1 = ds.GetDataElement( tag1 )
  el2 = ds.GetDataElement( tag2 )
  
  
  #pf = gdcm.PythonFilter()
  #pf.SetFile( reader.GetFile() )
  #print el1.GetTag()
  
  print el1.GetByteValue()
  v1 = eval(el1.GetByteValue().GetBuffer())
  print el2.GetByteValue()
  v2 = eval(el2.GetByteValue().GetBuffer())
  
  print v1
  shift = v1
  print v2
  scale = v2
  
  ss = vtk.vtkImageShiftScale()
  ss.SetInput( vtkreader.GetOutput() )
  # because VTK image shift / scale convention is inverted from DICOM make sure shift is 0
  assert shift == 0
  ss.SetShift( shift )
  ss.SetScale( scale )
  ss.SetOutputScalarTypeToUnsignedShort ()
  ss.Update()
  
  # vtkGDCMImageWriter does not support Sequence, so let's write a tmp file first:
  # Some operation will actually be discarded (we simply need a temp storage)
  vtkwriter = vtkgdcm.vtkGDCMImageWriter()
  vtkwriter.SetFileName( tmpfile )
  vtkwriter.SetMedicalImageProperties( vtkreader.GetMedicalImageProperties() )
  vtkwriter.SetDirectionCosines( vtkreader.GetDirectionCosines() )
  vtkwriter.SetImageFormat( reader.GetImageFormat() )
  # do not pass shift/scale again
  vtkwriter.SetInput( ss.GetOutput() )
  #vtkwriter.Update()
  vtkwriter.Write()
  
  # ok now rewrite the exact same file as the original (keep all info)
  # but use the Pixel Data Element from the written file
  tmpreader = gdcm.ImageReader()
  tmpreader.SetFileName( tmpfile )
  if not tmpreader.Read():
    sys.exit(1)
  
  writer = gdcm.ImageWriter()
  writer.SetFileName( outfilename )
  # Pass image from vtk written file
  writer.SetImage( tmpreader.GetImage() )
  # pass dataset from initial 'reader'
  writer.SetFile( reader.GetFile() )
  if not writer.Write():
    sys.exit(1)
Пример #9
0
    def img2dcm(self, input_img, output, img_type, img_number): 

        if img_type == "jpg":
            print "JPG"
            image = vtk.vtkJPEGReader()
            image.SetFileName(input_img)
            image.Update()
            
        elif img_type == "tif":
            print "TIF"
            image = vtk.vtkTIFFReader()
            image.SetFileName(input_img)
            image.Update()
            
        elif img_type == "bmp":
            print "BMP"
            image = vtk.vtkBMPReader()
            image.SetFileName(input_img)
            image.Allow8BitBMPOn()
            image.Update()
            
        elif img_type == "png": 
            print "PNG"
            image = vtk.vtkPNGReader()
            image.SetFileName(input_img)
            image.SetDataSpacing(self.spacing)
            image.Update()

        elif img_type == "vti": 
            print "VTI"
            image = vtk.vtkXMLImageDataReader()
            image.SetFileName(input_img)
            image.Update()
        
            #if (orientation == 0):
        image_pos = img_number * self.spacing[2]
        image_localization = image_pos

        # print image_pos, img_number, image.GetOutput().GetScalarRange()

        img_clone = vtk.vtkImageData()
        img_clone.DeepCopy(image.GetOutput())
        img_clone.SetSpacing(self.spacing)
        img_clone.Update()

        # v = vtk.vtkImageViewer()
        # v.SetInput(image.GetOutput())
        # v.SetColorLevel(500)
        # v.SetColorWindow(240)
        # v.Render()

        # time.sleep(3)

        # a = vtk.vtkImageCast()
        # a.SetOutputScalarTypeToUnsignedChar()
        # a.SetInput(image.GetOutput())
        # a.ClampOverflowOn()
        # a.Update()

        #b = vtk.vtkJPEGWriter()
        #b.SetFileName("C:\\teste.jpg")
        #b.SetInput(a.GetOutput())
        #b.writer()

        #spacing = image.GetOutput().GetSpacing()
        #elif (orientation == 1):
        #    image_pos[0] =  image_pos[0] + thickness
        #    image_localization = image_localization + thickness
        #    img_number = img_number + 1
        
        #elif (orientation == 2):
        #    image_pos[1] =  image_pos[1] + thickness
        #    image_localization = image_localization + thickness
        #    img_number = img_number + 1
        pos = 0, 0, image_pos
        print pos

        # transform = vtk.vtkTransform()
        # transform.Translate(pos)

        # transform_filter = vtk.vtkImageReslice()
        # transform_filter.SetInput(image.GetOutput())
        # transform_filter.SetResliceTransform(transform)
        # transform_filter.Update()

        properties = vtk.vtkMedicalImageProperties()
        properties.SetModality(self.modality)
        properties.SetInstitutionName(self.institution)
        properties.SetPatientName(self.patient)
        properties.SetSliceThickness(str(self.spacing[2]))
        properties.SetSeriesNumber(str(self.serie))
        properties.SetImageNumber(str(img_number))
        properties.SetPatientID(self.patient_id)
        properties.SetStudyID(self.study_id)
        properties.AddUserDefinedValue("Image Position (Patient)", "%.5f\\%.5f\\%.5f" %
                                       (pos[0], pos[1], pos[2]))
        properties.AddUserDefinedValue("Instance Number", str(img_number))
        print str(img_number), properties.GetNumberOfUserDefinedValues()

        writer = vtkgdcm.vtkGDCMImageWriter()
        writer.SetInput(img_clone)
        writer.SetStudyUID(self.study_uid)
        writer.SetSeriesUID(self.series_uid)
        writer.SetMedicalImageProperties(properties)
        writer.SetFileName(output)
        # writer.SetImageFormat(vtk.VTK_LUMINANCE)
        writer.SetFileDimensionality(3)
        writer.Write()
               
        reader = gdcm.Reader()
        reader.SetFileName(output)
        reader.Read()

        anon = gdcm.Anonymizer()
        anon.SetFile(reader.GetFile())
        anon.Replace(gdcm.Tag(0x0020, 0x0013), str(img_number))
        anon.Replace(gdcm.Tag(0x0028, 0x0030), "%.6f\\%.6f" % (self.spacing[0],
                                                               self.spacing[1]))

        writer = gdcm.Writer()
        writer.SetFile(reader.GetFile())
        writer.SetFileName(output)
        writer.Write()    

        # print spacing, pos, image.GetOutput().GetScalarRange()

        # writer = ivDicom.DicomWriter()
        # writer.SetFileName(output)
        # writer.SaveIsNew(image.GetOutput())
        # 
        # writer.SetAcquisitionModality(self.modality)
        # writer.SetInstitutionName(self.institution)
        # writer.SetStudyID(self.study_uid)
        # writer.SetPatientID(self.patient_id)
        # writer.SetPatientName(self.patient)
        # writer.SetImageThickness(self.spacing[2])
        # writer.SetImageSeriesNumber(self.serie)
        # writer.SetImageNumber(img_number)
        # writer.SetImagePosition(pos)
        # writer.SetImageLocation(image_localization)
        # writer.SetPixelSpacing(self.spacing[:2])
        # writer.Save()

        print "Written", input_img, "->", output
Пример #10
0
VTK_DATA_ROOT = vtkGetDataRoot()

r = vtkgdcm.vtkGDCMImageReader()
r.SetFileName(VTK_DATA_ROOT + "/Data/mr.001")
r.Update()

#print r.GetOutput()

# Pixel Spacing
# 0.78125, 0.78125, 0

# Image Position (Patient)
# -13.3034, -80.8219, 119.178

# try to rewrite it:
w = vtkgdcm.vtkGDCMImageWriter()
w.SetInput(r.GetOutput())
w.SetMedicalImageProperties(r.GetMedicalImageProperties())
w.SetDirectionCosines(r.GetDirectionCosines())
w.SetFileName("mr.001.dcm")
w.Write()

# beach.tif
#tiffreader = vtk.vtkTIFFReader()
#tiffreader.SetFileName( VTK_DATA_ROOT + "/Data/beach.tif" )
#tiffreader.Update()
# print tiffreader.GetOutput()
# -> TIFF reader was apparently broken in VTK until some very recent
# version and thus image appear upside down, unless you also update VTKData :(

jpegreader = vtk.vtkJPEGReader()
Пример #11
0
def ProcessOneFilePrivate(filename, outfilename, tmpfile):
    vtkreader = vtkgdcm.vtkGDCMImageReader()
    vtkreader.SetFileName(filename)
    vtkreader.Update()

    # (2005,1409)     DS      4       0.0
    # (2005,140a)     DS      16      1.52283272283272

    # (2005,0014)     LO      26      Philips MR Imaging DD 005
    tag1 = gdcm.PrivateTag(0x2005, 0x09, "Philips MR Imaging DD 005")
    tag2 = gdcm.PrivateTag(0x2005, 0x0a, "Philips MR Imaging DD 005")

    # Need to access some private tags, reread the file (for now):
    reader = gdcm.Reader()
    reader.SetFileName(filename)
    if not reader.Read():
        sys.exit(1)

    ds = reader.GetFile().GetDataSet()

    el1 = ds.GetDataElement(tag1)
    el2 = ds.GetDataElement(tag2)

    #pf = gdcm.PythonFilter()
    #pf.SetFile( reader.GetFile() )
    #print el1.GetTag()

    print el1.GetByteValue()
    v1 = eval(el1.GetByteValue().GetBuffer())
    print el2.GetByteValue()
    v2 = eval(el2.GetByteValue().GetBuffer())

    print v1
    shift = v1
    print v2
    scale = v2

    ss = vtk.vtkImageShiftScale()
    ss.SetInput(vtkreader.GetOutput())
    # because VTK image shift / scale convention is inverted from DICOM make sure shift is 0
    assert shift == 0
    ss.SetShift(shift)
    ss.SetScale(scale)
    ss.SetOutputScalarTypeToUnsignedShort()
    ss.Update()

    # vtkGDCMImageWriter does not support Sequence, so let's write a tmp file first:
    # Some operation will actually be discarded (we simply need a temp storage)
    vtkwriter = vtkgdcm.vtkGDCMImageWriter()
    vtkwriter.SetFileName(tmpfile)
    vtkwriter.SetMedicalImageProperties(vtkreader.GetMedicalImageProperties())
    vtkwriter.SetDirectionCosines(vtkreader.GetDirectionCosines())
    vtkwriter.SetImageFormat(reader.GetImageFormat())
    # do not pass shift/scale again
    vtkwriter.SetInput(ss.GetOutput())
    #vtkwriter.Update()
    vtkwriter.Write()

    # ok now rewrite the exact same file as the original (keep all info)
    # but use the Pixel Data Element from the written file
    tmpreader = gdcm.ImageReader()
    tmpreader.SetFileName(tmpfile)
    if not tmpreader.Read():
        sys.exit(1)

    writer = gdcm.ImageWriter()
    writer.SetFileName(outfilename)
    # Pass image from vtk written file
    writer.SetImage(tmpreader.GetImage())
    # pass dataset from initial 'reader'
    writer.SetFile(reader.GetFile())
    if not writer.Write():
        sys.exit(1)