Пример #1
0
def use_cmd_optargs(options, args):
    # If import DICOM argument...
    if options.dicom_dir:
        import_dir = options.dicom_dir
        Publisher.sendMessage('Import directory',
                              directory=import_dir,
                              use_gui=not options.no_gui)

        if options.save:
            Publisher.sendMessage('Save project',
                                  filepath=os.path.abspath(options.save))
            exit(0)

        check_for_export(options)

        return True
    elif options.import_folder:
        Publisher.sendMessage('Import folder', folder=options.import_folder)
        if options.save:
            Publisher.sendMessage('Save project',
                                  filepath=os.path.abspath(options.save))
            exit(0)
        check_for_export(options)

    elif options.import_all:
        import invesalius.reader.dicom_reader as dcm
        for patient in dcm.GetDicomGroups(options.import_all):
            for group in patient.GetGroups():
                Publisher.sendMessage('Import group',
                                      group=group,
                                      use_gui=not options.no_gui)
                check_for_export(options,
                                 suffix=group.title,
                                 remove_surfaces=False)
                Publisher.sendMessage('Remove masks', mask_indexes=(0, ))
        return True

    # Check if there is a file path somewhere in what the user wrote
    # In case there is, try opening as it was a inv3
    else:
        for arg in reversed(args):

            file = utils.decode(arg, FS_ENCODE)
            if os.path.isfile(file):
                path = os.path.abspath(file)
                Publisher.sendMessage('Open project', filepath=path)
                check_for_export(options)
                return True

            file = utils.decode(arg, sys.stdin.encoding)
            if os.path.isfile(file):
                path = os.path.abspath(file)
                Publisher.sendMessage('Open project', filepath=path)
                check_for_export(options)
                return True

    return False
Пример #2
0
def use_cmd_optargs(options, args):
    # If debug argument...
    if options.debug:
        Publisher.subscribe(print_events, Publisher.ALL_TOPICS)
        session = ses.Session()
        session.debug = 1

    # If import DICOM argument...
    if options.dicom_dir:
        import_dir = options.dicom_dir
        Publisher.sendMessage('Import directory', {
            'directory': import_dir,
            'gui': not options.no_gui
        })

        if options.save:
            Publisher.sendMessage('Save project',
                                  os.path.abspath(options.save))
            exit(0)

        check_for_export(options)

        return True
    elif options.import_all:
        import invesalius.reader.dicom_reader as dcm
        for patient in dcm.GetDicomGroups(options.import_all):
            for group in patient.GetGroups():
                Publisher.sendMessage('Import group', {
                    'group': group,
                    'gui': not options.no_gui
                })
                check_for_export(options,
                                 suffix=group.title,
                                 remove_surfaces=False)
                Publisher.sendMessage('Remove masks', [0])
        return True

    # Check if there is a file path somewhere in what the user wrote
    # In case there is, try opening as it was a inv3
    else:
        for arg in reversed(args):

            file = utils.decode(arg, FS_ENCODE)
            if os.path.isfile(file):
                path = os.path.abspath(file)
                Publisher.sendMessage('Open project', path)
                check_for_export(options)
                return True

            file = utils.decode(arg, sys.stdin.encoding)
            if os.path.isfile(file):
                path = os.path.abspath(file)
                Publisher.sendMessage('Open project', path)
                check_for_export(options)
                return True

    return False
Пример #3
0
def use_cmd_optargs(options, args):
    # If debug argument...
    if options.debug:
        Publisher.subscribe(print_events, Publisher.ALL_TOPICS)
        session = ses.Session()
        session.debug = 1

    # If import DICOM argument...
    if options.dicom_dir:
        import_dir = options.dicom_dir
        Publisher.sendMessage('Import directory', directory=import_dir, use_gui=not options.no_gui)

        if options.save:
            Publisher.sendMessage('Save project', filepath=os.path.abspath(options.save))
            exit(0)

        check_for_export(options)

        return True
    elif options.import_all:
        import invesalius.reader.dicom_reader as dcm
        for patient in dcm.GetDicomGroups(options.import_all):
            for group in patient.GetGroups():
                Publisher.sendMessage('Import group',
                                      group=group,
                                      use_gui=not options.no_gui)
                check_for_export(options, suffix=group.title, remove_surfaces=False)
                Publisher.sendMessage('Remove masks', mask_indexes=(0,))
        return True

    # Check if there is a file path somewhere in what the user wrote
    # In case there is, try opening as it was a inv3
    else:
        for arg in reversed(args):

            file = utils.decode(arg, FS_ENCODE)
            if os.path.isfile(file):
                path = os.path.abspath(file)
                Publisher.sendMessage('Open project', filepath=path)
                check_for_export(options)
                return True

            file = utils.decode(arg, sys.stdin.encoding)
            if os.path.isfile(file):
                path = os.path.abspath(file)
                Publisher.sendMessage('Open project', filepath=path)
                check_for_export(options)
                return True

    return False
Пример #4
0
    def SaveProject(self, path=None, compress=False):
        Publisher.sendMessage('Begin busy cursor')
        session = ses.Session()
        if path:
            dirpath, filename = os.path.split(path)
        else:
            dirpath, filename = session.project_path

        if isinstance(filename, str):
            filename = utils.decode(filename, const.FS_ENCODE)

        proj = prj.Project()
        try:
            prj.Project().SavePlistProject(dirpath, filename, compress)
        except PermissionError as err:
            if wx.GetApp() is None:
                print(
                    "Error: Permission denied, you don't have permission to write at {}"
                    .format(dirpath))
            else:
                dlg = dialogs.ErrorMessageBox(
                    None, "Save project error",
                    "It was not possible to save because you don't have permission to write at {}\n{}"
                    .format(dirpath, err))
                dlg.ShowModal()
                dlg.Destroy()
        else:
            session.SaveProject((dirpath, filename))

        Publisher.sendMessage('End busy cursor')
Пример #5
0
    def OnExportSurface(self, filename, filetype):
        ftype_prefix = {
            const.FILETYPE_STL: '.stl',
            const.FILETYPE_VTP: '.vtp',
            const.FILETYPE_PLY: '.ply',
            const.FILETYPE_STL_ASCII: '.stl',
        }
        if filetype in ftype_prefix:
            temp_file = tempfile.mktemp(suffix=ftype_prefix[filetype])

            if _has_win32api:
                utl.touch(temp_file)
                _temp_file = temp_file
                temp_file = win32api.GetShortPathName(temp_file)
                os.remove(_temp_file)

            temp_file = utl.decode(temp_file, const.FS_ENCODE)
            try:
                self._export_surface(temp_file, filetype)
            except ValueError:
                if wx.GetApp() is None:
                    print(
                        "It was not possible to export the surface because the surface is empty"
                    )
                else:
                    wx.MessageBox(
                        _("It was not possible to export the surface because the surface is empty"
                          ), _("Export surface error"))
                return

            shutil.move(temp_file, filename)
Пример #6
0
def Extract(filename, folder):
    if _has_win32api:
        folder = win32api.GetShortPathName(folder)
    folder = decode(folder, const.FS_ENCODE)

    tar = tarfile.open(filename, "r")
    idir = decode(os.path.split(tar.getnames()[0])[0], 'utf8')
    os.mkdir(os.path.join(folder, idir))
    filelist = []
    for t in tar.getmembers():
        fsrc = tar.extractfile(t)
        fname = os.path.join(folder, decode(t.name, 'utf-8'))
        fdst = open(fname, 'wb')
        shutil.copyfileobj(fsrc, fdst)
        filelist.append(fname)
        fsrc.close()
        fdst.close()
        del fsrc
        del fdst
    tar.close()
    return filelist
Пример #7
0
def Extract(filename, folder):
    if _has_win32api:
        folder = win32api.GetShortPathName(folder)
    folder = decode(folder, const.FS_ENCODE)

    tar = tarfile.open(filename, "r")
    idir = decode(os.path.split(tar.getnames()[0])[0], 'utf8')
    os.mkdir(os.path.join(folder, idir))
    filelist = []
    for t in tar.getmembers():
        fsrc = tar.extractfile(t)
        fname = os.path.join(folder, decode(t.name, 'utf-8'))
        fdst = open(fname, 'wb')
        shutil.copyfileobj(fsrc, fdst)
        filelist.append(fname)
        fsrc.close()
        fdst.close()
        del fsrc
        del fdst
    tar.close()
    return filelist
Пример #8
0
 def OnOpenOtherFiles(self, filepath):
     filepath = utils.decode(filepath, const.FS_ENCODE)
     if not (filepath) == None:
         name = os.path.basename(filepath).split(".")[0]
         group = oth.ReadOthers(filepath)
         if group:
             matrix, matrix_filename = self.OpenOtherFiles(group)
             self.CreateOtherProject(name, matrix, matrix_filename)
             self.LoadProject()
             Publisher.sendMessage("Enable state project", state=True)
         else:
             dialog.ImportInvalidFiles(ftype="Others")
Пример #9
0
    def OnOpenOtherFiles(self, filepath):
        filepath = utils.decode(filepath, const.FS_ENCODE)
        if not(filepath) == None:
            name = filepath.rpartition('\\')[-1].split('.')

            group = oth.ReadOthers(filepath)
            
            if group:
                matrix, matrix_filename = self.OpenOtherFiles(group)
                self.CreateOtherProject(str(name[0]), matrix, matrix_filename)
                self.LoadProject()
                Publisher.sendMessage("Enable state project", state=True)
            else:
                dialog.ImportInvalidFiles(ftype="Others")
Пример #10
0
    def OnOpenOtherFiles(self, pubsub_evt):
        filepath = utils.decode(pubsub_evt.data, const.FS_ENCODE)
        if not (filepath) == None:
            name = filepath.rpartition('\\')[-1].split('.')

            group = oth.ReadOthers(filepath)

            if group:
                matrix, matrix_filename = self.OpenOtherFiles(group)
                self.CreateOtherProject(str(name[0]), matrix, matrix_filename)
                self.LoadProject()
                Publisher.sendMessage("Enable state project", True)
            else:
                dialog.ImportInvalidFiles(ftype="Others")
Пример #11
0
def GetPixelSpacingFromInfoFile(filepath):
    filepath = utils.decode(filepath, const.FS_ENCODE)
    if filepath.endswith('.DS_Store'):
        return False
    fi = open(filepath, 'r')
    lines = fi.readlines()
    measure_scale = 'mm'
    values = []

    if len(lines) > 0:
        #info text from avizo
        if '# Avizo Stacked Slices' in lines[0]:
            value = lines[2].split(' ')
            spx = float(value[1])
            spy = float(value[2])
            value = lines[5].split(' ')
            spz = float(value[1])

            return [spx * 0.001, spy * 0.001, spz * 0.001]
        else:
            #info text from skyscan
            for l in lines:
                if 'Pixel Size' in l:
                    if 'um' in l:
                        measure_scale = 'um'
                    
                    value = l.split("=")[-1]
                    values.append(value)

            if len(values) > 0:
                value = values[-1]
                
                value = value.replace('\n','')
                value = value.replace('\r','')

                #convert um to mm (InVesalius default)
                if measure_scale == 'um':
                    value = float(value) * 0.001
                    measure_scale = 'mm'

                elif measure_scale == 'nm':
                    value = float(value) * 0.000001

                return [value, value, value]
            else:
                return False
    else:
        return False
Пример #12
0
def GetPixelSpacingFromInfoFile(filepath):
    filepath = utils.decode(filepath, const.FS_ENCODE)
    if filepath.endswith(".DS_Store"):
        return False
    fi = open(filepath, "r")
    lines = fi.readlines()
    measure_scale = "mm"
    values = []

    if len(lines) > 0:
        # info text from avizo
        if "# Avizo Stacked Slices" in lines[0]:
            value = lines[2].split(" ")
            spx = float(value[1])
            spy = float(value[2])
            value = lines[5].split(" ")
            spz = float(value[1])

            return [spx * 0.001, spy * 0.001, spz * 0.001]
        else:
            # info text from skyscan
            for l in lines:
                if "Pixel Size" in l:
                    if "um" in l:
                        measure_scale = "um"

                    value = l.split("=")[-1]
                    values.append(value)

            if len(values) > 0:
                value = values[-1]

                value = value.replace("\n", "")
                value = value.replace("\r", "")

                # convert um to mm (InVesalius default)
                if measure_scale == "um":
                    value = float(value) * 0.001
                    measure_scale = "mm"

                elif measure_scale == "nm":
                    value = float(value) * 0.000001

                return [value, value, value]
            else:
                return False
    else:
        return False
Пример #13
0
def GetPixelSpacingFromInfoFile(filepath):
    filepath = utils.decode(filepath, const.FS_ENCODE)
    if filepath.endswith('.DS_Store'):
        return False
    fi = open(filepath, 'r')
    lines = fi.readlines()
    measure_scale = 'mm'
    values = []

    if len(lines) > 0:
        #info text from avizo
        if '# Avizo Stacked Slices' in lines[0]:
            value = lines[2].split(' ')
            spx = float(value[1])
            spy = float(value[2])
            value = lines[5].split(' ')
            spz = float(value[1])

            return [spx * 0.001, spy * 0.001, spz * 0.001]
        else:
            #info text from skyscan
            for l in lines:
                if 'Pixel Size' in l:
                    if 'um' in l:
                        measure_scale = 'um'

                    value = l.split("=")[-1]
                    values.append(value)

            if len(values) > 0:
                value = values[-1]

                value = value.replace('\n', '')
                value = value.replace('\r', '')

                #convert um to mm (InVesalius default)
                if measure_scale == 'um':
                    value = float(value) * 0.001
                    measure_scale = 'mm'

                elif measure_scale == 'nm':
                    value = float(value) * 0.000001

                return [value, value, value]
            else:
                return False
    else:
        return False
Пример #14
0
    def SaveProject(self, path=None, compress=False):
        Publisher.sendMessage('Begin busy cursor')
        session = ses.Session()
        if path:
            dirpath, filename = os.path.split(path)
            session.SaveProject((dirpath, filename))
        else:
            dirpath, filename = session.project_path

        if isinstance(filename, str):
            filename = utils.decode(filename, const.FS_ENCODE)

        proj = prj.Project()
        prj.Project().SavePlistProject(dirpath, filename, compress)

        session.SaveProject()
        Publisher.sendMessage('End busy cursor')
Пример #15
0
    def OnExportSurface(self, filename, filetype):
        ftype_prefix = {
            const.FILETYPE_STL: '.stl',
            const.FILETYPE_VTP: '.vtp',
            const.FILETYPE_PLY: '.ply',
            const.FILETYPE_STL_ASCII: '.stl',
        }
        if filetype in ftype_prefix:
            temp_file = tempfile.mktemp(suffix=ftype_prefix[filetype])

            if _has_win32api:
                utl.touch(temp_file)
                _temp_file = temp_file
                temp_file = win32api.GetShortPathName(temp_file)
                os.remove(_temp_file)

            temp_file = utl.decode(temp_file, const.FS_ENCODE)
            try:
                self._export_surface(temp_file, filetype)
            except ValueError:
                if wx.GetApp() is None:
                    print(
                        "It was not possible to export the surface because the surface is empty"
                    )
                else:
                    wx.MessageBox(
                        _("It was not possible to export the surface because the surface is empty"
                          ), _("Export surface error"))
                return

            try:
                shutil.move(temp_file, filename)
            except PermissionError as err:
                dirpath = os.path.split(filename)[0]
                if wx.GetApp() is None:
                    print(
                        _("It was not possible to export the surface because you don't have permission to write to {} folder: {}"
                          .format(dirpath, err)))
                else:
                    dlg = dialogs.ErrorMessageBox(
                        None, _("Export surface error"),
                        "It was not possible to export the surface because you don't have permission to write to {}:\n{}"
                        .format(dirpath, err))
                    dlg.ShowModal()
                    dlg.Destroy()
                os.remove(temp_file)
Пример #16
0
    def SaveProject(self, path=None, compress=False):
        Publisher.sendMessage('Begin busy cursor')
        session = ses.Session()
        if path:
            dirpath, filename = os.path.split(path)
            session.SaveProject((dirpath, filename))
        else:
            dirpath, filename = session.project_path

        if isinstance(filename, str):
            filename = utils.decode(filename, const.FS_ENCODE)

        proj = prj.Project()
        prj.Project().SavePlistProject(dirpath, filename, compress)

        session.SaveProject()
        Publisher.sendMessage('End busy cursor')
Пример #17
0
def Compress(folder, filename, filelist, compress=False):
    tmpdir, tmpdir_ = os.path.split(folder)
    current_dir = os.path.abspath(".")
    temp_inv3 = tempfile.mktemp()
    if _has_win32api:
        touch(temp_inv3)
        temp_inv3 = win32api.GetShortPathName(temp_inv3)

    temp_inv3 = decode(temp_inv3, const.FS_ENCODE)
    #os.chdir(tmpdir)
    #file_list = glob.glob(os.path.join(tmpdir_,"*"))
    if compress:
        tar = tarfile.open(temp_inv3, "w:gz")
    else:
        tar = tarfile.open(temp_inv3, "w")
    for name in filelist:
        tar.add(name, arcname=os.path.join(tmpdir_, filelist[name]))
    tar.close()
    shutil.move(temp_inv3, filename)
Пример #18
0
def Compress(folder, filename, filelist, compress=False):
    tmpdir, tmpdir_ = os.path.split(folder)
    current_dir = os.path.abspath(".")
    temp_inv3 = tempfile.mktemp()
    if _has_win32api:
        touch(temp_inv3)
        temp_inv3 = win32api.GetShortPathName(temp_inv3)

    temp_inv3 = decode(temp_inv3, const.FS_ENCODE)
    #os.chdir(tmpdir)
    #file_list = glob.glob(os.path.join(tmpdir_,"*"))
    if compress:
        tar = tarfile.open(temp_inv3, "w:gz")
    else:
        tar = tarfile.open(temp_inv3, "w")
    for name in filelist:
        tar.add(name, arcname=os.path.join(tmpdir_, filelist[name]))
    tar.close()
    shutil.move(temp_inv3, filename)
Пример #19
0
    def OnExportSurface(self, filename, filetype):
        ftype_prefix = {
            const.FILETYPE_STL: '.stl',
            const.FILETYPE_VTP: '.vtp',
            const.FILETYPE_PLY: '.ply',
            const.FILETYPE_STL_ASCII: '.stl',
        }
        if filetype in ftype_prefix:
            temp_file = tempfile.mktemp(suffix=ftype_prefix[filetype])

            if _has_win32api:
                utl.touch(temp_file)
                _temp_file = temp_file
                temp_file = win32api.GetShortPathName(temp_file)
                os.remove(_temp_file)

            temp_file = utl.decode(temp_file, const.FS_ENCODE)
            self._export_surface(temp_file, filetype)

            shutil.move(temp_file, filename)
Пример #20
0
    def OnExportSurface(self, filename, filetype):
        ftype_prefix = {
            const.FILETYPE_STL: '.stl',
            const.FILETYPE_VTP: '.vtp',
            const.FILETYPE_PLY: '.ply',
            const.FILETYPE_STL_ASCII: '.stl',
        }
        if filetype in ftype_prefix:
            temp_file = tempfile.mktemp(suffix=ftype_prefix[filetype])

            if _has_win32api:
                utl.touch(temp_file)
                _temp_file = temp_file
                temp_file = win32api.GetShortPathName(temp_file)
                os.remove(_temp_file)

            temp_file = utl.decode(temp_file, const.FS_ENCODE)
            self._export_surface(temp_file, filetype)

            shutil.move(temp_file, filename)
Пример #21
0
    _("Vasculature - Hard"): (240, 80),
    _("Vasculature - Soft"): (650, 160),
    _("Contour"): (255, 127)
}

REDUCE_IMAGEDATA_QUALITY = 0

# PATHS
FS_ENCODE = sys.getfilesystemencoding()

if sys.platform == 'win32':
    from invesalius.expanduser import expand_user
    try:
        USER_DIR = expand_user()
    except:
        USER_DIR = utils.decode(os.path.expanduser('~'), FS_ENCODE)
else:
    USER_DIR = utils.decode(os.path.expanduser('~'), FS_ENCODE)

USER_INV_DIR = os.path.join(USER_DIR, u'.invesalius')
USER_PRESET_DIR = os.path.join(USER_INV_DIR, u'presets')
USER_LOG_DIR = os.path.join(USER_INV_DIR, u'logs')

FILE_PATH = utils.decode(os.path.split(__file__)[0], FS_ENCODE)

if hasattr(sys,"frozen") and (sys.frozen == "windows_exe"\
                            or sys.frozen == "console_exe"):
    abs_path = os.path.abspath(FILE_PATH, u'..', u'..', u'..')
    ICON_DIR = os.path.join(abs_path, u"icons")
    SAMPLE_DIR = os.path.join(FILE_PATH, u'samples')
    DOC_DIR = os.path.join(FILE_PATH, u'docs')
Пример #22
0
 def SetLastDicomFolder(self, folder):
     self.last_dicom_folder = decode(folder, FS_ENCODE)
     self.WriteSessionFile()
Пример #23
0
    def SavePlistProject(self, dir_, filename, compress=False):
        dir_temp = decode(tempfile.mkdtemp(), const.FS_ENCODE)

        self.compress = compress

        filename_tmp = os.path.join(dir_temp, u'matrix.dat')
        filelist = {}

        project = {
                   # Format info
                   "format_version": const.INVESALIUS_ACTUAL_FORMAT_VERSION,
                   "invesalius_version": const.INVESALIUS_VERSION,
                   "date": datetime.datetime.now().isoformat(),
                   "compress": self.compress,

                   # case info
                   "name": self.name, # patient's name
                   "modality": self.modality, # CT, RMI, ...
                   "orientation": self.original_orientation,
                   "window_width": self.window,
                   "window_level": self.level,
                   "scalar_range": self.threshold_range,
                   "spacing": self.spacing,
                   "affine": self.affine,
                  }

        # Saving the matrix containing the slices
        matrix = {
            'filename': u'matrix.dat',
            'shape': self.matrix_shape,
            'dtype': self.matrix_dtype,
        }
        project['matrix'] = matrix
        filelist[self.matrix_filename] = 'matrix.dat'
        #shutil.copyfile(self.matrix_filename, filename_tmp)

        # Saving the masks
        masks = {}
        for index in self.mask_dict:
            masks[str(index)] = self.mask_dict[index].SavePlist(dir_temp,
                                                                filelist)
        project['masks'] = masks

        # Saving the surfaces
        surfaces = {}
        for index in self.surface_dict:
            surfaces[str(index)] = self.surface_dict[index].SavePlist(dir_temp,
                                                                     filelist)
        project['surfaces'] = surfaces

        # Saving the measurements
        measurements = self.GetMeasuresDict()
        measurements_filename = 'measurements.plist'
        temp_mplist = tempfile.mktemp() 
        plistlib.writePlist(measurements, 
                            temp_mplist)
        filelist[temp_mplist] = measurements_filename
        project['measurements'] = measurements_filename

        # Saving the annotations (empty in this version)
        project['annotations'] = {}

        # Saving the main plist
        temp_plist = tempfile.mktemp()
        plistlib.writePlist(project, temp_plist)
        filelist[temp_plist] = 'main.plist'

        # Compressing and generating the .inv3 file
        path = os.path.join(dir_,filename)
        Compress(dir_temp, path, filelist, compress)

        # Removing the temp folder.
        shutil.rmtree(dir_temp)

        for f in filelist:
            if filelist[f].endswith('.plist'):
                os.remove(f)
Пример #24
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)
Пример #25
0
 def __init__(self, grouper, filepath):
     self.grouper = grouper
     self.filepath = utils.decode(filepath, const.FS_ENCODE)
     self.run()
Пример #26
0
    def SavePlistProject(self, dir_, filename, compress=False):
        dir_temp = decode(tempfile.mkdtemp(), const.FS_ENCODE)

        self.compress = compress

        filename_tmp = os.path.join(dir_temp, u'matrix.dat')
        filelist = {}

        project = {
            # Format info
            "format_version": const.INVESALIUS_ACTUAL_FORMAT_VERSION,
            "invesalius_version": const.INVESALIUS_VERSION,
            "date": datetime.datetime.now().isoformat(),
            "compress": self.compress,

            # case info
            "name": self.name,  # patient's name
            "modality": self.modality,  # CT, RMI, ...
            "orientation": self.original_orientation,
            "window_width": self.window,
            "window_level": self.level,
            "scalar_range": self.threshold_range,
            "spacing": self.spacing,
            "affine": self.affine,
        }

        # Saving the matrix containing the slices
        matrix = {
            'filename': u'matrix.dat',
            'shape': self.matrix_shape,
            'dtype': self.matrix_dtype,
        }
        project['matrix'] = matrix
        filelist[self.matrix_filename] = 'matrix.dat'
        #shutil.copyfile(self.matrix_filename, filename_tmp)

        # Saving the masks
        masks = {}
        for index in self.mask_dict:
            masks[str(index)] = self.mask_dict[index].SavePlist(
                dir_temp, filelist)
        project['masks'] = masks

        # Saving the surfaces
        surfaces = {}
        for index in self.surface_dict:
            surfaces[str(index)] = self.surface_dict[index].SavePlist(
                dir_temp, filelist)
        project['surfaces'] = surfaces

        # Saving the measurements
        measurements = self.GetMeasuresDict()
        measurements_filename = 'measurements.plist'
        temp_mplist = tempfile.mktemp()
        plistlib.writePlist(measurements, temp_mplist)
        filelist[temp_mplist] = measurements_filename
        project['measurements'] = measurements_filename

        # Saving the annotations (empty in this version)
        project['annotations'] = {}

        # Saving the main plist
        temp_plist = tempfile.mktemp()
        plistlib.writePlist(project, temp_plist)
        filelist[temp_plist] = 'main.plist'

        # Compressing and generating the .inv3 file
        path = os.path.join(dir_, filename)
        Compress(dir_temp, path, filelist, compress)

        # Removing the temp folder.
        shutil.rmtree(dir_temp)

        for f in filelist:
            if filelist[f].endswith('.plist'):
                os.remove(f)
Пример #27
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)
Пример #28
0
    def __init__(self, bmp_file, filepath):
        self.bmp_file = bmp_file
        self.filepath = utils.decode(filepath, const.FS_ENCODE)

        self.run()
Пример #29
0
 def __init__(self, grouper, filepath):
     self.grouper = grouper
     self.filepath = utils.decode(filepath, const.FS_ENCODE)
     self.run()
Пример #30
0
 def __init__(self, bmp_file, filepath):
     self.bmp_file = bmp_file
     self.filepath = utils.decode(filepath, const.FS_ENCODE)
     
     self.run()
Пример #31
0
                _("Vasculature - Hard"):(240,80),
                _("Vasculature - Soft"):(650,160),
                _("Contour"): (255, 127)}

REDUCE_IMAGEDATA_QUALITY = 0


# PATHS
FS_ENCODE = sys.getfilesystemencoding()

if sys.platform == 'win32':
    from invesalius.expanduser import expand_user
    try:
        USER_DIR = expand_user()
    except:
        USER_DIR = utils.decode(os.path.expanduser('~'), FS_ENCODE)
else:
    USER_DIR = utils.decode(os.path.expanduser('~'), FS_ENCODE)

USER_INV_DIR = os.path.join(USER_DIR, u'.invesalius')
USER_PRESET_DIR = os.path.join(USER_INV_DIR, u'presets')
USER_LOG_DIR = os.path.join(USER_INV_DIR, u'logs')

FILE_PATH = utils.decode(os.path.split(__file__)[0], FS_ENCODE)

if hasattr(sys,"frozen") and (sys.frozen == "windows_exe"\
                            or sys.frozen == "console_exe"):
    abs_path = os.path.abspath(FILE_PATH, u'..', u'..', u'..')
    ICON_DIR = os.path.join(abs_path, u"icons")
    SAMPLE_DIR = os.path.join(FILE_PATH, u'samples')
    DOC_DIR = os.path.join(FILE_PATH, u'docs')
Пример #32
0
#        _SplashScreen = wx.SplashScreen


import invesalius.gui.language_dialog as lang_dlg
import invesalius.i18n as i18n
import invesalius.session as ses
import invesalius.utils as utils

FS_ENCODE = sys.getfilesystemencoding()

if sys.platform == 'win32':
    from invesalius.expanduser import expand_user
    try:
        USER_DIR = expand_user()
    except:
        USER_DIR = utils.decode(os.path.expanduser('~'), FS_ENCODE)
else:
    USER_DIR = utils.decode(os.path.expanduser('~'),FS_ENCODE)

USER_INV_DIR = os.path.join(USER_DIR, u'.invesalius')
USER_PRESET_DIR = os.path.join(USER_INV_DIR, u'presets')
USER_RAYCASTING_PRESETS_DIRECTORY = os.path.join(USER_PRESET_DIR, u'raycasting')
USER_LOG_DIR = os.path.join(USER_INV_DIR, u'logs')

# ------------------------------------------------------------------

if sys.platform in ('linux2', 'linux', 'win32'):
    try:
        tmp_var = wx.GetXDisplay
    except AttributeError:
        # A workaround to make InVesalius run with wxPython4 from Ubuntu 18.04
Пример #33
0
#        _SplashScreen = wx.SplashScreen


import invesalius.gui.language_dialog as lang_dlg
import invesalius.i18n as i18n
import invesalius.session as ses
import invesalius.utils as utils

FS_ENCODE = sys.getfilesystemencoding()

if sys.platform == 'win32':
    from invesalius.expanduser import expand_user
    try:
        USER_DIR = expand_user()
    except:
        USER_DIR = utils.decode(os.path.expanduser('~'), FS_ENCODE)
else:
    USER_DIR = utils.decode(os.path.expanduser('~'),FS_ENCODE)

USER_INV_DIR = os.path.join(USER_DIR, u'.invesalius')
USER_PRESET_DIR = os.path.join(USER_INV_DIR, u'presets')
USER_RAYCASTING_PRESETS_DIRECTORY = os.path.join(USER_PRESET_DIR, u'raycasting')
USER_LOG_DIR = os.path.join(USER_INV_DIR, u'logs')

# ------------------------------------------------------------------

if sys.platform in ('linux2', 'linux', 'win32'):
    try:
        tmp_var = wx.GetXDisplay
    except AttributeError:
        # A workaround to make InVesalius run with wxPython4 from Ubuntu 18.04