Ejemplo n.º 1
0
    def GetDicomGroups(self, path, recursive):

        if not const.VTK_WARNING:
            log_path = utils.encode(
                os.path.join(const.USER_LOG_DIR, 'vtkoutput.txt'),
                const.FS_ENCODE)
            fow = vtk.vtkFileOutputWindow()
            fow.SetFileName(log_path)
            ow = vtk.vtkOutputWindow()
            ow.SetInstance(fow)

        y = yGetDicomGroups(path, recursive)
        for value_progress in y:
            print(">>>>", value_progress)
            if not self.running:
                break
            if isinstance(value_progress, tuple):
                self.UpdateLoadFileProgress(value_progress)
            else:
                self.EndLoadFile(value_progress)
        self.UpdateLoadFileProgress(None)

        #Is necessary in the case user cancel
        #the load, ensure that dicomdialog is closed
        if (self.stoped):
            self.UpdateLoadFileProgress(None)
            self.stoped = False
Ejemplo n.º 2
0
    def GetFilenameList(self):
        # Should be called when user selects this group
        # This list will be used to create the vtkImageData
        # (interpolated)

        if _has_win32api:
            filelist = [win32api.GetShortPathName(dicom.image.file)
                        for dicom in
                        self.slices_dict.values()]
        else:
            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)
        try:
            sorter.Sort([utils.encode(i, const.FS_ENCODE) for i in filelist])
        except TypeError:
            sorter.Sort(filelist)
        filelist = sorter.GetFilenames()

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

        return filelist
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)

        if _has_win32api:
            filelist = [win32api.GetShortPathName(dicom.image.file)
                        for dicom in
                        self.slices_dict.values()]
        else:
            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)
            try:
                sorter.Sort([utils.encode(i, const.FS_ENCODE) for i in filelist])
            except TypeError:
                sorter.Sort(filelist)
            filelist = sorter.GetFilenames()

        # for breast-CT of koning manufacturing (KBCT)
        if list(self.slices_dict.values())[0].parser.GetManufacturerName() == "Koning":
            filelist.sort()
        
        return filelist
Ejemplo n.º 4
0
    def GetDicomGroups(self, path, recursive):

        if not const.VTK_WARNING:
            log_path = utils.encode(os.path.join(const.USER_LOG_DIR, 'vtkoutput.txt'), const.FS_ENCODE)
            fow = vtk.vtkFileOutputWindow()
            fow.SetFileName(log_path)
            ow = vtk.vtkOutputWindow()
            ow.SetInstance(fow)

        y = yGetDicomGroups(path, recursive)
        for value_progress in y:
            print(">>>>", value_progress)
            if not self.running:
                break
            if isinstance(value_progress, tuple):
                self.UpdateLoadFileProgress(value_progress)
            else:
                self.EndLoadFile(value_progress)
        self.UpdateLoadFileProgress(None)

        #Is necessary in the case user cancel
        #the load, ensure that dicomdialog is closed
        if(self.stoped):
            self.UpdateLoadFileProgress(None)
            self.stoped = False   
Ejemplo n.º 5
0
def create_dicom_thumbnails(filename, window=None, level=None):
    rvtk = vtkgdcm.vtkGDCMImageReader()
    rvtk.SetFileName(utils.encode(filename, const.FS_ENCODE))
    rvtk.Update()

    img = rvtk.GetOutput()
    if window is None or level is None:
        _min, _max = img.GetScalarRange()
        window = _max - _min
        level = _min + window / 2

    dx, dy, dz = img.GetDimensions()

    if dz > 1:
        thumbnail_paths = []
        for i in range(dz):
            img_slice = ExtractVOI(img, 0, dx-1, 0, dy-1, i, i+1)

            colorer = vtk.vtkImageMapToWindowLevelColors()
            colorer.SetInputData(img_slice)
            colorer.SetWindow(window)
            colorer.SetLevel(level)
            colorer.SetOutputFormatToRGB()
            colorer.Update()

            resample = vtk.vtkImageResample()
            resample.SetInputData(colorer.GetOutput())
            resample.SetAxisMagnificationFactor ( 0, 0.25 )
            resample.SetAxisMagnificationFactor ( 1, 0.25 )
            resample.SetAxisMagnificationFactor ( 2, 1 )
            resample.Update()

            thumbnail_path = tempfile.mktemp()

            write_png = vtk.vtkPNGWriter()
            write_png.SetInputData(resample.GetOutput())
            write_png.SetFileName(thumbnail_path)
            write_png.Write()

            thumbnail_paths.append(thumbnail_path)

        return thumbnail_paths
    else:
        colorer = vtk.vtkImageMapToWindowLevelColors()
        colorer.SetInputData(img)
        colorer.SetWindow(window)
        colorer.SetLevel(level)
        colorer.SetOutputFormatToRGB()
        colorer.Update()

        resample = vtk.vtkImageResample()
        resample.SetInputData(colorer.GetOutput())
        resample.SetAxisMagnificationFactor ( 0, 0.25 )
        resample.SetAxisMagnificationFactor ( 1, 0.25 )
        resample.SetAxisMagnificationFactor ( 2, 1 )
        resample.Update()

        thumbnail_path = tempfile.mktemp()

        write_png = vtk.vtkPNGWriter()
        write_png.SetInputData(resample.GetOutput())
        write_png.SetFileName(thumbnail_path)
        write_png.Write()

        return thumbnail_path
Ejemplo n.º 6
0
    def run(self):
        grouper = self.grouper
        reader = gdcm.ImageReader()
        if _has_win32api:
            try:
                reader.SetFileName(
                    utils.encode(win32api.GetShortPathName(self.filepath),
                                 const.FS_ENCODE))
            except TypeError:
                reader.SetFileName(win32api.GetShortPathName(self.filepath))
        else:
            try:
                reader.SetFileName(utils.encode(self.filepath,
                                                const.FS_ENCODE))
            except TypeError:
                reader.SetFileName(self.filepath)
        if (reader.Read()):
            file = reader.GetFile()
            # Retrieve data set
            dataSet = file.GetDataSet()
            # Retrieve header
            header = file.GetHeader()
            stf = gdcm.StringFilter()
            stf.SetFile(file)

            field_dict = {}
            data_dict = {}

            tag = gdcm.Tag(0x0008, 0x0005)
            ds = reader.GetFile().GetDataSet()
            if ds.FindDataElement(tag):
                encoding_value = str(
                    ds.GetDataElement(tag).GetValue()).split('\\')[0]

                if encoding_value.startswith("Loaded"):
                    encoding = "ISO_IR 100"
                else:
                    try:
                        encoding = const.DICOM_ENCODING_TO_PYTHON[
                            encoding_value]
                    except KeyError:
                        encoding = 'ISO_IR 100'
            else:
                encoding = "ISO_IR 100"

            # Iterate through the Header
            iterator = header.GetDES().begin()
            while (not iterator.equal(header.GetDES().end())):
                dataElement = iterator.next()
                if not dataElement.IsUndefinedLength():
                    tag = dataElement.GetTag()
                    data = stf.ToStringPair(tag)
                    stag = tag.PrintAsPipeSeparatedString()

                    group = str(tag.GetGroup())
                    field = str(tag.GetElement())

                    tag_labels[stag] = data[0]

                    if not group in data_dict.keys():
                        data_dict[group] = {}

                    if not (utils.VerifyInvalidPListCharacter(data[1])):
                        data_dict[group][field] = utils.decode(
                            data[1], encoding)
                    else:
                        data_dict[group][field] = "Invalid Character"

            # Iterate through the Data set
            iterator = dataSet.GetDES().begin()
            while (not iterator.equal(dataSet.GetDES().end())):
                dataElement = iterator.next()
                if not dataElement.IsUndefinedLength():
                    tag = dataElement.GetTag()
                    #  if (tag.GetGroup() == 0x0009 and tag.GetElement() == 0x10e3) \
                    #  or (tag.GetGroup() == 0x0043 and tag.GetElement() == 0x1027):
                    #  continue
                    data = stf.ToStringPair(tag)
                    stag = tag.PrintAsPipeSeparatedString()

                    group = str(tag.GetGroup())
                    field = str(tag.GetElement())

                    tag_labels[stag] = data[0]

                    if not group in data_dict.keys():
                        data_dict[group] = {}

                    if not (utils.VerifyInvalidPListCharacter(data[1])):
                        data_dict[group][field] = utils.decode(
                            data[1], encoding, 'replace')
                    else:
                        data_dict[group][field] = "Invalid Character"

            # -------------- To Create DICOM Thumbnail -----------

            try:
                data = data_dict[str(0x028)][str(0x1050)]
                level = [float(value) for value in data.split('\\')][0]
                data = data_dict[str(0x028)][str(0x1051)]
                window = [float(value) for value in data.split('\\')][0]
            except (KeyError, ValueError):
                level = None
                window = None

            if _has_win32api:
                thumbnail_path = imagedata_utils.create_dicom_thumbnails(
                    win32api.GetShortPathName(self.filepath), window, level)
            else:
                thumbnail_path = imagedata_utils.create_dicom_thumbnails(
                    self.filepath, window, level)

            #------ Verify the orientation --------------------------------

            img = reader.GetImage()
            direc_cosines = img.GetDirectionCosines()
            orientation = gdcm.Orientation()
            try:
                _type = orientation.GetType(tuple(direc_cosines))
            except TypeError:
                _type = orientation.GetType(direc_cosines)
            label = orientation.GetLabel(_type)

            # ----------   Refactory --------------------------------------
            data_dict['invesalius'] = {'orientation_label': label}

            # -------------------------------------------------------------
            dict_file[self.filepath] = data_dict

            #----------  Verify is DICOMDir -------------------------------
            is_dicom_dir = 1
            try:
                if (data_dict[str(0x002)][str(0x002)] !=
                        "1.2.840.10008.1.3.10"):  #DICOMDIR
                    is_dicom_dir = 0
            except (KeyError):
                is_dicom_dir = 0

            if not (is_dicom_dir):
                parser = dicom.Parser()
                parser.SetDataImage(dict_file[self.filepath], self.filepath,
                                    thumbnail_path)

                dcm = dicom.Dicom()
                #self.l.acquire()
                dcm.SetParser(parser)
                grouper.AddFile(dcm)
Ejemplo n.º 7
0
    def run(self):
        grouper = self.grouper
        reader = gdcm.ImageReader()
        if _has_win32api:
            try:
                reader.SetFileName(utils.encode(win32api.GetShortPathName(self.filepath),
                                                const.FS_ENCODE))
            except TypeError:
                reader.SetFileName(win32api.GetShortPathName(self.filepath))
        else:
            try:
                reader.SetFileName(utils.encode(self.filepath, const.FS_ENCODE))
            except TypeError:
                reader.SetFileName(self.filepath)
        if (reader.Read()):
            file = reader.GetFile()
            # Retrieve data set
            dataSet = file.GetDataSet()
            # Retrieve header
            header = file.GetHeader()
            stf = gdcm.StringFilter()
            stf.SetFile(file)

            field_dict = {}
            data_dict = {}

            tag = gdcm.Tag(0x0008, 0x0005)
            ds = reader.GetFile().GetDataSet()
            if ds.FindDataElement(tag):
                encoding_value = str(ds.GetDataElement(tag).GetValue()).split('\\')[0]
                
                if encoding_value.startswith("Loaded"):
                    encoding = "ISO_IR 100"
                else:
                    try:
                        encoding = const.DICOM_ENCODING_TO_PYTHON[encoding_value]
                    except KeyError:
                        encoding = 'ISO_IR 100'
            else:
                encoding = "ISO_IR 100"

            # Iterate through the Header
            iterator = header.GetDES().begin()
            while (not iterator.equal(header.GetDES().end())):
                dataElement = iterator.next()
                if not dataElement.IsUndefinedLength():
                    tag = dataElement.GetTag()
                    data = stf.ToStringPair(tag)
                    stag = tag.PrintAsPipeSeparatedString()

                    group = str(tag.GetGroup())
                    field = str(tag.GetElement())

                    tag_labels[stag] = data[0]

                    if not group in data_dict.keys():
                        data_dict[group] = {}

                    if not(utils.VerifyInvalidPListCharacter(data[1])):
                        data_dict[group][field] = utils.decode(data[1], encoding)
                    else:
                        data_dict[group][field] = "Invalid Character"

            # Iterate through the Data set
            iterator = dataSet.GetDES().begin()
            while (not iterator.equal(dataSet.GetDES().end())):
                dataElement = iterator.next()
                if not dataElement.IsUndefinedLength():
                    tag = dataElement.GetTag()
                    #  if (tag.GetGroup() == 0x0009 and tag.GetElement() == 0x10e3) \
                            #  or (tag.GetGroup() == 0x0043 and tag.GetElement() == 0x1027):
                        #  continue
                    data = stf.ToStringPair(tag)
                    stag = tag.PrintAsPipeSeparatedString()

                    group = str(tag.GetGroup())
                    field = str(tag.GetElement())

                    tag_labels[stag] = data[0]

                    if not group in data_dict.keys():
                        data_dict[group] = {}

                    if not(utils.VerifyInvalidPListCharacter(data[1])):
                        data_dict[group][field] = utils.decode(data[1], encoding, 'replace')
                    else:
                        data_dict[group][field] = "Invalid Character"


            # -------------- To Create DICOM Thumbnail -----------


            try:
                data = data_dict[str(0x028)][str(0x1050)]
                level = [float(value) for value in data.split('\\')][0]
                data = data_dict[str(0x028)][str(0x1051)]
                window =  [float(value) for value in data.split('\\')][0]
            except(KeyError, ValueError):
                level = None
                window = None

            if _has_win32api:
                thumbnail_path = imagedata_utils.create_dicom_thumbnails(win32api.GetShortPathName(self.filepath), window, level)
            else:
                thumbnail_path = imagedata_utils.create_dicom_thumbnails(self.filepath, window, level)

            #------ Verify the orientation --------------------------------

            img = reader.GetImage()
            direc_cosines = img.GetDirectionCosines()
            orientation = gdcm.Orientation()
            try:
                _type = orientation.GetType(tuple(direc_cosines))
            except TypeError:
                _type = orientation.GetType(direc_cosines)
            label = orientation.GetLabel(_type)

 
            # ----------   Refactory --------------------------------------
            data_dict['invesalius'] = {'orientation_label' : label}

            # -------------------------------------------------------------
            dict_file[self.filepath] = data_dict
            
            #----------  Verify is DICOMDir -------------------------------
            is_dicom_dir = 1
            try: 
                if (data_dict[str(0x002)][str(0x002)] != "1.2.840.10008.1.3.10"): #DICOMDIR
                    is_dicom_dir = 0
            except(KeyError):
                    is_dicom_dir = 0
                                        
            if not(is_dicom_dir):
                parser = dicom.Parser()
                parser.SetDataImage(dict_file[self.filepath], self.filepath, thumbnail_path)
                
                dcm = dicom.Dicom()
                #self.l.acquire()
                dcm.SetParser(parser)
                grouper.AddFile(dcm)
Ejemplo n.º 8
0
def create_dicom_thumbnails(filename, window=None, level=None):
    rvtk = vtkgdcm.vtkGDCMImageReader()
    rvtk.SetFileName(utils.encode(filename, const.FS_ENCODE))
    rvtk.Update()

    img = rvtk.GetOutput()
    if window is None or level is None:
        _min, _max = img.GetScalarRange()
        window = _max - _min
        level = _min + window / 2

    dx, dy, dz = img.GetDimensions()

    if dz > 1:
        thumbnail_paths = []
        for i in range(dz):
            img_slice = ExtractVOI(img, 0, dx-1, 0, dy-1, i, i+1)

            colorer = vtk.vtkImageMapToWindowLevelColors()
            colorer.SetInputData(img_slice)
            colorer.SetWindow(window)
            colorer.SetLevel(level)
            colorer.SetOutputFormatToRGB()
            colorer.Update()

            resample = vtk.vtkImageResample()
            resample.SetInputData(colorer.GetOutput())
            resample.SetAxisMagnificationFactor ( 0, 0.25 )
            resample.SetAxisMagnificationFactor ( 1, 0.25 )
            resample.SetAxisMagnificationFactor ( 2, 1 )
            resample.Update()

            thumbnail_path = tempfile.mktemp()

            write_png = vtk.vtkPNGWriter()
            write_png.SetInputData(resample.GetOutput())
            write_png.SetFileName(thumbnail_path)
            write_png.Write()

            thumbnail_paths.append(thumbnail_path)

        return thumbnail_paths
    else:
        colorer = vtk.vtkImageMapToWindowLevelColors()
        colorer.SetInputData(img)
        colorer.SetWindow(window)
        colorer.SetLevel(level)
        colorer.SetOutputFormatToRGB()
        colorer.Update()

        resample = vtk.vtkImageResample()
        resample.SetInputData(colorer.GetOutput())
        resample.SetAxisMagnificationFactor ( 0, 0.25 )
        resample.SetAxisMagnificationFactor ( 1, 0.25 )
        resample.SetAxisMagnificationFactor ( 2, 1 )
        resample.Update()

        thumbnail_path = tempfile.mktemp()

        write_png = vtk.vtkPNGWriter()
        write_png.SetInputData(resample.GetOutput())
        write_png.SetFileName(thumbnail_path)
        write_png.Write()

        return thumbnail_path