Ejemplo n.º 1
0
def SortFiles(filelist, dicom):
    # Sort slices
    # FIXME: Coronal Crash. necessary verify
    if (dicom.image.orientation_label != "CORONAL"):
        ##Organize reversed image
        sorter = gdcm.IPPSorter()
        sorter.SetComputeZSpacing(True)
        sorter.SetZSpacingTolerance(1e-10)
        sorter.Sort(filelist)

        #Getting organized image
        filelist = sorter.GetFilenames()

    return filelist
Ejemplo n.º 2
0
def dcm2mmap(input_dir, output_mmap):
    tmp_dcm_files = glob.glob(os.path.join(input_dir, '*'))

    sorter = gdcm.IPPSorter()
    sorter.Sort(tmp_dcm_files)
    dcm_files = sorter.GetFilenames()

    if not dcm_files:
        dcm_files = sorted(tmp_dcm_files)

    r = vtkgdcm.vtkGDCMImageReader()
    r.SetFileName(dcm_files[0])
    r.Update()

    x, y, z = r.GetOutput().GetDimensions()
    
    a_size = len(dcm_files), y, x
    t = numpy_support.get_numpy_array_type(r.GetDataScalarType())
    print t

    print t, a_size
    m_dcm = numpy.memmap(output_mmap, mode='w+', dtype='int16', shape=a_size)

    lp = 0
    zspacing = 0

    for i, dcm_file in enumerate(dcm_files):
        r = vtkgdcm.vtkGDCMImageReader()
        r.SetFileName(dcm_file)
        r.Update()

        if lp:
            zspacing += abs(r.GetImagePositionPatient()[2] - lp)
        lp = r.GetImagePositionPatient()[2]

        o = r.GetOutput()
        d = numpy_support.vtk_to_numpy(o.GetPointData().GetScalars())

        m_dcm[i] = d.reshape(y, x)

    m_dcm.flush()

    xs, ys, zs = o.GetSpacing()
    spacing = xs, ys, zspacing / (len(dcm_files) - 1.0)
    print spacing
    return m_dcm, spacing
Ejemplo n.º 3
0
    def GetFilenameList(self):
        # Should be called when user selects this group
        # This list will be used to create the vtkImageData
        # (interpolated)

        filelist = [dicom.image.file for dicom in self.slices_dict.values()]

        # Sort slices using GDCM
        if (self.dicom.image.orientation_label <> "CORONAL"):
            #Organize reversed image
            sorter = gdcm.IPPSorter()
            sorter.SetComputeZSpacing(True)
            sorter.SetZSpacingTolerance(1e-10)
            sorter.Sort(filelist)
            filelist = sorter.GetFilenames()

            #Getting organized image
        return filelist
Ejemplo n.º 4
0
    def GetFilenameList(self):
        # Should be called when user selects this group
        # This list will be used to create the vtkImageData
        # (interpolated)

        filelist = [dicom.image.file for dicom in self.slices_dict.values()]

        # Sort slices using GDCM
        if (self.dicom.image.orientation_label <> "CORONAL"):
            #Organize reversed image
            sorter = gdcm.IPPSorter()
            sorter.SetComputeZSpacing(True)
            sorter.SetZSpacingTolerance(1e-10)
            sorter.Sort(filelist)
            filelist = sorter.GetFilenames()

        # for breast-CT of koning manufacturing (KBCT)
        if self.slices_dict.values()[0].parser.GetManufacturerName(
        ) == "Koning":
            filelist.sort()

        return filelist
Ejemplo n.º 5
0
    def _handler_ipp_sort(self, event):
        # get out current Study instance
        study = self._study_dict[self._selected_study_uid]
        # then the series_dict belonging to that Study
        series_dict = study.series_dict
        # and finally the specific series instance
        series = series_dict[self._selected_series_uid]

        # have to  cast to normal strings (from unicode)
        filenames = [str(i) for i in series.filenames]

        sorter = gdcm.IPPSorter()
        ret = sorter.Sort(filenames)

        if not ret:
            self._module_manager.log_error(
                'Could not sort DICOM filenames. ' +
                'It could be that this is an invalid collection.')
            return

        selected_idx = -1
        del series.filenames[:]
        for idx, fn in enumerate(sorter.GetFilenames()):
            series.filenames.append(fn)
            if idx >= 0 and fn == self._current_filename:
                selected_idx = idx

        lc = self._view_frame.files_lc

        # now overwrite the listctrl with these sorted filenames
        self._helper_files_to_files_listctrl(series.filenames)

        # select the file that was selected prior to the sort
        if selected_idx >= 0:
            lc.Select(selected_idx)
            lc.Focus(selected_idx)
Ejemplo n.º 6
0
############################################################################
#
#  Program: GDCM (Grassroots DICOM). A DICOM library
#  Module:  $URL$
#
#  Copyright (c) 2006-2010 Mathieu Malaterre
#  All rights reserved.
#  See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details.
#
#     This software is distributed WITHOUT ANY WARRANTY; without even
#     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
#     PURPOSE.  See the above copyright notice for more information.
#
############################################################################

import gdcm
import os, sys

if __name__ == "__main__":
    sucess = 0
    s = gdcm.IPPSorter()
    # black box test:
    if not s.Sort([]):
        sys.exit(1)

    sys.exit(0)
Ejemplo n.º 7
0
    def execute_module(self):
        # have to  cast to normal strings (from unicode)
        filenames = [str(i) for i in self._config.dicom_filenames]

        # make sure all is zeroed.
        self._reader.SetFileName(None)
        self._reader.SetFileNames(None)

        # we only sort and derive slice-based spacing if there are
        # more than 1 filenames
        if len(filenames) > 1:
            sorter = gdcm.IPPSorter()
            sorter.SetComputeZSpacing(True)
            sorter.SetZSpacingTolerance(1e-2)

            ret = sorter.Sort(filenames)
            alpha_sorted = False
            if not ret:
                if self._config.robust_spacing:
                    self._module_manager.log_warning(
                        'Could not sort DICOM filenames by IPP. Doing alphabetical sorting.')
                    filenames.sort()
                    alpha_sorted = True
                    
                else:
                    raise RuntimeError(
                    'Could not sort DICOM filenames before loading.')

            if sorter.GetZSpacing() == 0.0 and not alpha_sorted:
                msg = 'DICOM IPP sorting yielded incorrect results.'
                raise RuntimeError(msg)

            # then give the reader the sorted list of files
            sa = vtk.vtkStringArray()
            if alpha_sorted:
                flist = filenames
            else:
                flist = sorter.GetFilenames()
                
            for fn in flist: 
                sa.InsertNextValue(fn)

            self._reader.SetFileNames(sa)

        elif len(filenames) == 1:
            self._reader.SetFileName(filenames[0])

        else:
            raise RuntimeError(
                    'No DICOM filenames to read.')

        # now do the actual reading
        self._reader.Update()

        # see what the reader thinks the spacing is
        spacing = list(self._reader.GetDataSpacing())

        if len(filenames) > 1 and not alpha_sorted:
            # after the reader has done its thing,
            # impose derived spacing on the vtkImageChangeInformation
            # (by default it takes the SpacingBetweenSlices, which is
            # not always correct)
            spacing[2] = sorter.GetZSpacing()

        # single or multiple filenames, we have to set the correct
        # output spacing on the image change information
        print "SPACING: ", spacing
        self._ici.SetOutputSpacing(spacing)
        self._ici.Update()


        # integrate DirectionCosines into output data ###############
        # DirectionCosines: first two columns are X and Y in the LPH
        # coordinate system
        dc = self._reader.GetDirectionCosines()

        x_cosine = \
                dc.GetElement(0,0), dc.GetElement(1,0), dc.GetElement(2,0)
        y_cosine = \
                dc.GetElement(0,1), dc.GetElement(1,1), dc.GetElement(2,1)

        # calculate plane normal (z axis) in LPH coordinate system by taking the cross product
        norm = [0,0,0]
        vtk.vtkMath.Cross(x_cosine, y_cosine, norm)

        xl = misc_utils.major_axis_from_iop_cosine(x_cosine)
        yl = misc_utils.major_axis_from_iop_cosine(y_cosine)

        # vtkGDCMImageReader swaps the y (to fit the VTK convention),
        # but does not flip the DirectionCosines here, so we do that.
        # (only if the reader is flipping)
        if yl and not self._reader.GetFileLowerLeft():
            yl = tuple((yl[1], yl[0]))

        zl = misc_utils.major_axis_from_iop_cosine(norm)

        lut = {'L' : 0, 'R' : 1, 'P' : 2, 'A' : 3, 'F' : 4, 'H' : 5}
    
        if xl and yl and zl:
            # add this data as a vtkFieldData
            fd = self._ici.GetOutput().GetFieldData()

            axis_labels_array = vtk.vtkIntArray()
            axis_labels_array.SetName('axis_labels_array')

            for l in xl + yl + zl:
                axis_labels_array.InsertNextValue(lut[l])

            fd.AddArray(axis_labels_array)