Esempio n. 1
0
    def testOutputWindow(self):
        a = vtk.vtkOutputWindow()
        b = vtk.vtkOutputWindow()
        self.assertNotEqual(a, b)

        c = vtk.vtkOutputWindow.GetInstance()
        d = vtk.vtkOutputWindow.GetInstance()
        self.assertIs(c, d)
Esempio n. 2
0
    def OpenPlistProject(self, filename):
        import invesalius.data.measures as ms
        import invesalius.data.mask as msk
        import invesalius.data.surface as srf

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

        filelist = Extract(filename, tempfile.mkdtemp())
        dirpath = os.path.abspath(os.path.split(filelist[0])[0])

        # Opening the main file from invesalius 3 project
        main_plist = os.path.join(dirpath, 'main.plist')
        project = plistlib.readPlist(main_plist)

        # case info
        self.name = project["name"]
        self.modality = project["modality"]
        self.original_orientation = project["orientation"]
        self.window = project["window_width"]
        self.level = project["window_level"]
        self.threshold_range = project["scalar_range"]
        self.spacing = project["spacing"]

        # Opening the matrix containing the slices
        filepath = os.path.join(dirpath, project["matrix"]["filename"])
        self.matrix_filename = filepath
        self.matrix_shape = project["matrix"]['shape']
        self.matrix_dtype = project["matrix"]['dtype']

        # Opening the masks
        self.mask_dict = {}
        for index in project["masks"]:
            filename = project["masks"][index]
            filepath = os.path.join(dirpath, filename)
            m = msk.Mask()
            m.OpenPList(filepath)
            self.mask_dict[m.index] = m

        # Opening the surfaces
        self.surface_dict = {}
        for index in project["surfaces"]:
            filename = project["surfaces"][index]
            filepath = os.path.join(dirpath, filename)
            s = srf.Surface(int(index))
            s.OpenPList(filepath)
            self.surface_dict[s.index] = s

        # Opening the measurements
        self.measurement_dict = {}
        measurements = plistlib.readPlist(
            os.path.join(dirpath, project["measurements"]))
        for index in measurements:
            measure = ms.Measurement()
            measure.Load(measurements[index])
            self.measurement_dict[int(index)] = measure
Esempio n. 3
0
def set_vtk_log():
    import vtk
    log_path = os.path.join("log.ini")
    fow = vtk.vtkFileOutputWindow()
    fow.SetFileName(log_path)
    ow = vtk.vtkOutputWindow()
    ow.SetInstance(fow)
Esempio n. 4
0
    def OpenPlistProject(self, filename):
        import invesalius.data.measures as ms
        import invesalius.data.mask as msk
        import invesalius.data.surface as srf
        
        if not const.VTK_WARNING:
            log_path = os.path.join(const.LOG_FOLDER, 'vtkoutput.txt')
            fow = vtk.vtkFileOutputWindow()
            fow.SetFileName(log_path)
            ow = vtk.vtkOutputWindow()
            ow.SetInstance(fow)
            
        filelist = Extract(filename, tempfile.mkdtemp())
        dirpath = os.path.abspath(os.path.split(filelist[0])[0])

        # Opening the main file from invesalius 3 project
        main_plist =  os.path.join(dirpath ,'main.plist')
        project = plistlib.readPlist(main_plist)

        # case info
        self.name = project["name"]
        self.modality = project["modality"]
        self.original_orientation = project["orientation"]
        self.window = project["window_width"]
        self.level = project["window_level"]
        self.threshold_range = project["scalar_range"]
        self.spacing = project["spacing"]

        # Opening the matrix containing the slices
        filepath = os.path.join(dirpath, project["matrix"]["filename"])
        self.matrix_filename = filepath
        self.matrix_shape = project["matrix"]['shape']
        self.matrix_dtype = project["matrix"]['dtype']

        # Opening the masks
        self.mask_dict = {}
        for index in project["masks"]:
            filename = project["masks"][index]
            filepath = os.path.join(dirpath, filename)
            m = msk.Mask()
            m.OpenPList(filepath)
            self.mask_dict[m.index] = m

        # Opening the surfaces
        self.surface_dict = {}
        for index in project["surfaces"]:
            filename = project["surfaces"][index]
            filepath = os.path.join(dirpath, filename)
            s = srf.Surface(int(index))
            s.OpenPList(filepath)
            self.surface_dict[s.index] = s

        # Opening the measurements
        self.measurement_dict = {}
        measurements = plistlib.readPlist(os.path.join(dirpath,
                                                       project["measurements"]))
        for index in measurements:
            measure = ms.Measurement()
            measure.Load(measurements[index])
            self.measurement_dict[int(index)] = measure
Esempio n. 5
0
def ReadOthers(dir_):
    """
    Read the given Analyze, NIfTI, Compressed NIfTI or PAR/REC file,
    remove singleton image dimensions and convert image orientation to
    RAS+ canonical coordinate system. Analyze header does not support
    affine transformation matrix, though cannot be converted automatically
    to canonical orientation.

    :param dir_: file path
    :return: imagedata object
    """

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

    try:
        imagedata = nib.squeeze_image(nib.load(dir_))
        imagedata = nib.as_closest_canonical(imagedata)
        imagedata.update_header()
    except (nib.filebasedimages.ImageFileError):
        return False

    return imagedata
Esempio n. 6
0
    def OpenPlistProject(self, filename):
        import data.measures as ms
 
        if not const.VTK_WARNING:
            log_path = os.path.join(const.LOG_FOLDER, 'vtkoutput.txt')
            fow = vtk.vtkFileOutputWindow()
            fow.SetFileName(log_path)
            ow = vtk.vtkOutputWindow()
            ow.SetInstance(fow)
            
        filelist = Extract(filename, tempfile.mkdtemp())
        main_plist = min(filter(lambda x: x.endswith('.plist'), filelist),
                         key=lambda x: len(x))
        project = plistlib.readPlist(main_plist)
        dirpath = os.path.abspath(os.path.split(filelist[0])[0])

        for key in project:
            if key == 'imagedata':
                filepath = os.path.split(project[key]["$vti"])[-1]
                path = os.path.join(dirpath, filepath)
                self.imagedata = iu.Import(path)
            elif key == 'presets':
                filepath = os.path.split(project[key]["#plist"])[-1]
                path = os.path.join(dirpath, filepath)
                p = Presets()
                p.OpenPlist(path)
                self.presets = p
            elif key == 'dicom_sample':
                path = os.path.join(dirpath, project[key])
                p = dicom.Parser()
                p.SetFileName(path)
                d = dicom.Dicom()
                d.SetParser(p)
                self.dicom_sample = d

            elif key == 'mask_dict':
                self.mask_dict = {}
                for mask in project[key]:
                    filepath = os.path.split(project[key][mask]["#mask"])[-1]
                    path = os.path.join(dirpath, filepath)
                    m = msk.Mask()
                    m.OpenPList(path)
                    self.mask_dict[m.index] = m
            elif key == 'surface_dict':
                self.surface_dict = {}
                for surface in project[key]:
                    filepath = os.path.split(project[key][surface]["#surface"])[-1]
                    path = os.path.join(dirpath, filepath)
                    s = srf.Surface()
                    s.OpenPList(path)
                    self.surface_dict[s.index] = s
            elif key == 'measurement_dict':
                self.measurement_dict = {}
                d = project['measurement_dict']
                for index in d:
                    measure = ms.Measurement()
                    measure.Load(d[index])
                    self.measurement_dict[int(index)] = measure
            else: 
                setattr(self, key, project[key])
Esempio n. 7
0
    def __init__(self, config):
        self.roi_physical_size = config["ROI_specs"]["roi_physical_size"]
        self.roi_physical_nvoxel = config["ROI_specs"]["roi_physical_nvoxel"]
        self.default_ct_value = config["ROI_specs"]["default_ct_value"]

        vtk_out = vtk.vtkOutputWindow()
        vtk_out.SetInstance(vtk_out)
Esempio n. 8
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
Esempio n. 9
0
def ReadOthers(dir_):
    """
    Read the given Analyze, NIfTI, Compressed NIfTI or PAR/REC file,
    remove singleton image dimensions and convert image orientation to
    RAS+ canonical coordinate system. Analyze header does not support
    affine transformation matrix, though cannot be converted automatically
    to canonical orientation.

    :param dir_: file path
    :return: imagedata object
    """

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

    try:
        imagedata = nib.squeeze_image(nib.load(dir_))
        imagedata = nib.as_closest_canonical(imagedata)
        imagedata.update_header()
    except(nib.filebasedimages.ImageFileError):
        return False

    return imagedata
Esempio n. 10
0
def send_errors_to_logging():
    """Send all VTK error/warning messages to Python's logging module."""
    error_output = vtk.vtkStringOutputWindow()
    error_win = vtk.vtkOutputWindow()
    error_win.SetInstance(error_output)
    obs = Observer()
    return obs.observe(error_output)
Esempio n. 11
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   
Esempio n. 12
0
def vis_bw(ax, a, facecolor='r'):
    # verts, faces, normals, values = measure.marching_cubes_lewiner(a, 0)
    # print(verts)
    # mesh = Poly3DCollection(verts[faces], alpha=0.5)
    # mesh.set_facecolor(facecolor)
    # ax.add_collection3d(mesh)

    # v_a = numpy_support.numpy_to_vtk(num_array=a.ravel(), deep=True, array_type=vtk.VTK_STRUCTURED_POINTS)
    # v_a = vtk.vtkDataObject()
    # v_a.SetInformation(v_bit_a)

    # n2vtk = vtk.vtkImageImport()  # Converter
    # n2vtk.SetArr
    #
    # contour = vtk.vtkDiscreteMarchingCubes()
    # contour.SetInputData(v_a)
    # contour.SetValue(0, .5)
    # contour.Update()

    # writer = vtk.vtkPolyDataWriter()
    # writer.SetInputData(contour)
    # writer.SetFileName('contour.vtk')
    # writer.Update()
    # mc = vtk.vtkMarchingCubes(v_a)
    # print(v_a)

    n_a = np.ravel(sitk.GetArrayFromImage(a), order='C')

    v_a = vtk.vtkImageData()
    v_a.SetSpacing(a.GetSpacing())
    v_a.SetOrigin(a.GetOrigin())
    v_a.SetDimensions(a.GetSize())
    print(a.GetPixelID())
    v_a.SetScalarType(convertTypeITKtoVTK(sitk.sitkInt8), vtk.vtkInformation())
    v_a.SetNumberOfScalarComponents(a.GetNumberOfComponentsPerPixel(),
                                    vtk.vtkInformation())

    print('a')
    v_a_to_VTK = numpy_to_vtk(n_a,
                              deep=True,
                              array_type=convertTypeITKtoVTK(a.GetPixelID()))
    print('b')
    v_a.GetPointData().SetScalars(v_a_to_VTK)

    fow = vtk.vtkFileOutputWindow()
    fow.SetFileName('ow.txt')

    ow = vtk.vtkOutputWindow()
    ow.SetInstance(fow)

    contour = vtk.vtkDiscreteMarchingCubes()
    contour.SetInputData(v_a)
    contour.SetValue(0, .5)
    contour.Update()

    writer = vtk.vtkPolyDataWriter()
    writer.SetInputData(contour.GetOutput())
    writer.SetFileName('contour.vtk')
    writer.Update()
Esempio n. 13
0
def setup_vtk_err(setup_qt):
    """ Used to send VTK errors to file instead of screen. """

    err_out = vtk.vtkFileOutputWindow()
    err_out.SetFileName('tests/output/vtk.err.txt')
    vtk_std_err = vtk.vtkOutputWindow()
    vtk_std_err.SetInstance(err_out)
    return vtk_std_err, setup_qt
Esempio n. 14
0
    def picker_callback(self, picker):
        global LIST_AMF_OBJECTS, CURRENT_SELECTED_OBJECT, DICT_MATERIAL

        # Catch the errors here
        output = vtk.vtkFileOutputWindow()
        output.SetFileName("log.txt")
        vtk.vtkOutputWindow().SetInstance(output)

        picker_outside = True
        # Check if the object picked belongs to our LIST_AMF_OBJECTS
        for i in range(len(LIST_AMF_OBJECTS)):
            if picker.actor in LIST_AMF_OBJECTS[i].geometry.actor.actors:
                # The user picked an object in our LIST_AMF_OBJECTS
                picker_outside = False

                # Update the visualization
                LIST_AMF_OBJECTS[
                    i].geometry.actor.mapper.scalar_visibility = False  # Disable the scalar colors assigned to the object
                LIST_AMF_OBJECTS[i].geometry.actor.property.color = (
                    1, 0, 0)  # Color the picked object in red
                LIST_AMF_OBJECTS[
                    i].geometry.actor.property.line_width = 8  # Increase slighly the size of the wireframe edges

                # Update the GUI
                self.GUI_OBJECT_NAME = LIST_AMF_OBJECTS[i].name
                self.GUI_ID = LIST_AMF_OBJECTS[i].xmlObjectID
                self.GUI_MATERIAL_ID = LIST_AMF_OBJECTS[i].materialId
                self.GUI_MATERIAL_NAME = DICT_MATERIAL[
                    LIST_AMF_OBJECTS[i].materialId]

                CURRENT_SELECTED_OBJECT = i
                # LIST_AMF_OBJECTS[i].geometry.actor.actor.scale = (1,1,2) # Just a placeholder in case we want to slightly increase the height of the selected object
            else:
                # The object was not picked - Reapply the original Scalar Color and line width
                LIST_AMF_OBJECTS[
                    i].geometry.actor.mapper.scalar_visibility = True
                LIST_AMF_OBJECTS[i].geometry.actor.property.line_width = 2
                # LIST_AMF_OBJECTS[i].geometry.actor.actor.scale = (1,1,1) # Just a placeholder to assign the orignal height to the object

        if picker_outside:
            # The picker did not select an object belonging to our LIST_AMF_OBJECTS
            self.GUI_MATERIAL_ID = ""
            self.GUI_OBJECT_NAME = ""
            self.GUI_ID = "No Object Selected"
            self.GUI_MATERIAL_NAME = ""
            CURRENT_SELECTED_OBJECT = -1
Esempio n. 15
0
def set_error_output_file(filename):
    """Set a file to write out the VTK errors."""
    filename = os.path.abspath(os.path.expanduser(filename))
    fileOutputWindow = vtk.vtkFileOutputWindow()
    fileOutputWindow.SetFileName(filename)
    outputWindow = vtk.vtkOutputWindow()
    outputWindow.SetInstance(fileOutputWindow)
    return fileOutputWindow, outputWindow
Esempio n. 16
0
 def __init__(self, config):
     self.config = config
     # Get VTK errors to console instead of stupid flashing window
     vtk_out = vtk.vtkOutputWindow()
     vtk_out.SetInstance(vtk_out)
     # self.device, self.model = self._get_device_and_load_model()
     self.logger = config.get_logger('predict')
     self.device, self.model = self._get_device_and_load_model_from_url()
Esempio n. 17
0
    def OpenPlistProject(self, filename):
        if not const.VTK_WARNING:
            log_path = os.path.join(inv_paths.USER_LOG_DIR, 'vtkoutput.txt')
            fow = vtk.vtkFileOutputWindow()
            fow.SetFileName(log_path.encode(const.FS_ENCODE))
            ow = vtk.vtkOutputWindow()
            ow.SetInstance(fow)

        filelist = Extract(filename, tempfile.mkdtemp())
        dirpath = os.path.abspath(os.path.split(filelist[0])[0])
        self.load_from_folder(dirpath)
Esempio n. 18
0
    def setupLogging(self):
        """ setup local login """
        import os
        temp = os.path.split(os.tempnam())[0]
        app = ''.join(c for c in self.appName if 'a' <= c.lower() <= 'z') + '.log.'
        logName = os.path.join(temp, app)

        fileOutputWindow = vtk.vtkFileOutputWindow()
        fileOutputWindow.SetFileName(logName)

        outputWindow = vtk.vtkOutputWindow().GetInstance()
        if outputWindow:
            outputWindow.SetInstance(fileOutputWindow)
Esempio n. 19
0
def test_ball_sim():
    '''
    Drawing the ball and animating with mlab
    '''

    from mayavi import mlab
    import time

    # to prevent error messages
    import vtk
    output = vtk.vtkFileOutputWindow()
    output.SetFileName("log.txt")
    vtk.vtkOutputWindow().SetInstance(output)

    p = np.array([0.8197, -1.62, 0.32])
    #init_vel = np.array([-2.2230, 5.7000, 2.8465])
    orange = (0.9100, 0.4100, 0.1700)
    s = mlab.points3d(p[0], p[1], p[2], color=orange, scale_factor=0.05)
    for i in range(10):
        #time.sleep(0.2)
        p = p + 0.01
        s.mlab_source.set(x=p[0], y=p[1], z=p[2])
Esempio n. 20
0
def VtkRead(filepath, t):
    if not const.VTK_WARNING:
        log_path = os.path.join(const.USER_LOG_DIR, 'vtkoutput.txt')
        fow = vtk.vtkFileOutputWindow()
        fow.SetFileName(log_path.encode(const.FS_ENCODE))
        ow = vtk.vtkOutputWindow()
        ow.SetInstance(fow)

    global no_error

    if t == "bmp":
        reader = vtk.vtkBMPReader()

    elif t == "tiff" or t == "tif":
        reader = vtk.vtkTIFFReader()

    elif t == "png":
        reader = vtk.vtkPNGReader()

    elif t == "jpeg" or t == "jpg":
        reader = vtk.vtkJPEGReader()

    else:
        return False

    print ">>>> bmp reader", type(filepath)

    reader.AddObserver("ErrorEvent", VtkErrorToPy)
    reader.SetFileName(filepath.encode(const.FS_ENCODE))
    reader.Update()

    if no_error:
        image = reader.GetOutput()
        dim = image.GetDimensions()

        if reader.GetNumberOfScalarComponents() > 1:
            luminanceFilter = vtk.vtkImageLuminance()
            luminanceFilter.SetInputData(image)
            luminanceFilter.Update()

            image = vtk.vtkImageData()
            image.DeepCopy(luminanceFilter.GetOutput())

        img_array = numpy_support.vtk_to_numpy(
            image.GetPointData().GetScalars())
        img_array.shape = (dim[1], dim[0])

        return img_array
    else:
        no_error = True
        return False
Esempio n. 21
0
File: app.py Progetto: jcdinis/POMES
    def __init__(self, parent, id, style):
        wx.Panel.__init__(self, parent, id, style=style)
        self.build_gui()
        self.__bind_events_wx()
        #self.__bind_events_pb()

        self.Show()

        # funcão para escrever o erro
        log_path = os.path.join('.' , 'vtkoutput.txt')
        fow = vtk.vtkFileOutputWindow()
        fow.SetFileName(log_path)
        ow = vtk.vtkOutputWindow()
        ow.SetInstance(fow)
Esempio n. 22
0
    def __init__(self, parent, id, style):
        wx.Panel.__init__(self, parent, id, style=style)
        self.build_gui()
        self.__bind_events_wx()
        self.__bind_events_pb()

        self.Show()

        # Error description
        log_path = os.path.join('.', 'vtkoutput.txt')
        fow = vtk.vtkFileOutputWindow()
        fow.SetFileName(log_path)
        ow = vtk.vtkOutputWindow()
        ow.SetInstance(fow)
Esempio n. 23
0
def VtkRead(filepath, t):
    if not const.VTK_WARNING:
        log_path = os.path.join(inv_paths.USER_LOG_DIR, 'vtkoutput.txt')
        fow = vtk.vtkFileOutputWindow()
        fow.SetFileName(log_path.encode(const.FS_ENCODE))
        ow = vtk.vtkOutputWindow()
        ow.SetInstance(fow)

    global no_error

    if t == "bmp":
        reader = vtk.vtkBMPReader()

    elif t == "tiff" or t == "tif":
        reader = vtk.vtkTIFFReader()

    elif t == "png":
        reader = vtk.vtkPNGReader()
    
    elif t == "jpeg" or t == "jpg":
        reader = vtk.vtkJPEGReader()

    else:
        return False

    reader.AddObserver("ErrorEvent", VtkErrorToPy)
    reader.SetFileName(filepath)
    reader.Update()
    
    if no_error:
        image = reader.GetOutput()
        dim = image.GetDimensions()
       
        if reader.GetNumberOfScalarComponents() > 1:
            luminanceFilter = vtk.vtkImageLuminance()
            luminanceFilter.SetInputData(image)
            luminanceFilter.Update()

            image = vtk.vtkImageData()
            image.DeepCopy(luminanceFilter.GetOutput())

        img_array = numpy_support.vtk_to_numpy(image.GetPointData().GetScalars())
        img_array.shape = (dim[1], dim[0])

        return img_array
    else:
        no_error = True
        return False
Esempio n. 24
0
    def _setupLogging(self):
        """ setup local logging """
        if not self.logFile:
            import os
            import tempfile

            temp = tempfile.gettempdir()
            app = "".join(c for c in self.appName if "a" <= c.lower() <= "z") + ".log."
            self.logFile = os.path.join(temp, app)

        fileOutputWindow = vtk.vtkFileOutputWindow()
        fileOutputWindow.SetFileName(self.logFile)

        outputWindow = vtk.vtkOutputWindow().GetInstance()
        if outputWindow:
            outputWindow.SetInstance(fileOutputWindow)
Esempio n. 25
0
    def _setupLogging(self):
        """ setup local logging """
        if not self.logFile:
            import os
            import tempfile
            temp = tempfile.gettempdir()
            app = ''.join(
                c for c in self.appName if 'a' <= c.lower() <= 'z') + '.log.'
            self.logFile = os.path.join(temp, app)

        fileOutputWindow = vtk.vtkFileOutputWindow()
        fileOutputWindow.SetFileName(self.logFile)

        outputWindow = vtk.vtkOutputWindow().GetInstance()
        if outputWindow:
            outputWindow.SetInstance(fileOutputWindow)
Esempio n. 26
0
    def __init__(self, parent, id, style):
        wx.Panel.__init__(self, parent, id, style=style)

        # usa da wx com a vtk junto (colocação do vtk dentro de wx)

        self.renderer = vtk.vtkRenderer()
        self.Interactor = wxVTKRenderWindowInteractor(self,
                                                      -1,
                                                      size=self.GetSize())
        self.Interactor.GetRenderWindow().AddRenderer(self.renderer)
        self.Interactor.Render()
        #-----------------------------------------------------------------------------
        #------- ajeitaro estilo da camera
        istyle = vtk.vtkInteractorStyleTrackballCamera()

        self.Interactor.SetInteractorStyle(istyle)
        #---------------------------------------------------------------

        self.VerPlano = False  # inicializar o plano, para usar como plano de corte

        self.Bind(wx.EVT_IDLE,
                  self.Restabelecer)  #para funcionar o editor de corte

        # funcão para escrever o erro num ficheiro txt
        log_path = os.path.join('.', 'vtkoutput.txt')
        fow = vtk.vtkFileOutputWindow()
        fow.SetFileName(log_path)
        ow = vtk.vtkOutputWindow()
        ow.SetInstance(fow)
        #--------------------------------------------------------
        #-------Criar a caixa de trabalho
        hbox = wx.BoxSizer(wx.VERTICAL)
        hbox.Add(wx.StaticText(self, -1, 'Area de Corte'))
        hbox.Add(self.Interactor, 1,
                 wx.EXPAND)  # juntar com o wx, numa so janela

        self.SetSizer(hbox)
        #------------------------------------------------------------------

        self.adicionaeixos()  #adiconar a função que chama o eixos
Esempio n. 27
0
    def CreateImageData(self, filelist, zspacing, size, bits):
        message = _("Generating multiplanar visualization...")

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

        x,y = size
        px, py = utils.predict_memory(len(filelist), x, y, bits)
        utils.debug("Image Resized to >>> %f x %f" % (px, py))

        if (x == px) and (y == py):
            const.REDUCE_IMAGEDATA_QUALITY = 0
        else:
            const.REDUCE_IMAGEDATA_QUALITY = 1

        if not(const.REDUCE_IMAGEDATA_QUALITY):
            update_progress= vtk_utils.ShowProgress(1, dialog_type = "ProgressDialog")

            array = vtk.vtkStringArray()
            for x in range(len(filelist)):
                if not self.running:
                    return False
                array.InsertValue(x,filelist[x])

            if not self.running:
                return False
            reader = vtkgdcm.vtkGDCMImageReader()
            reader.SetFileNames(array)
            reader.AddObserver("ProgressEvent", lambda obj,evt:
                         update_progress(reader,message))
            reader.Update()

            if not self.running:
                reader.AbortExecuteOn()
                return False
            # The zpacing is a DicomGroup property, so we need to set it
            imagedata = vtk.vtkImageData()
            imagedata.DeepCopy(reader.GetOutput())
            spacing = imagedata.GetSpacing()
            imagedata.SetSpacing(spacing[0], spacing[1], zspacing)
        else:

            update_progress= vtk_utils.ShowProgress(2*len(filelist),
                                                dialog_type = "ProgressDialog")

            # Reformat each slice and future append them
            appender = vtk.vtkImageAppend()
            appender.SetAppendAxis(2) #Define Stack in Z


            # Reformat each slice
            for x in range(len(filelist)):
                # TODO: We need to check this automatically according
                # to each computer's architecture
                # If the resolution of the matrix is too large
                if not self.running:
                    return False
                reader = vtkgdcm.vtkGDCMImageReader()
                reader.SetFileName(filelist[x])
                reader.AddObserver("ProgressEvent", lambda obj,evt:
                             update_progress(reader,message))
                reader.Update()

                #Resample image in x,y dimension
                slice_imagedata = ResampleImage2D(reader.GetOutput(), px, py, update_progress)
                #Stack images in Z axes
                appender.AddInput(slice_imagedata)
                #appender.AddObserver("ProgressEvent", lambda obj,evt:update_progress(appender))
                appender.Update()

            # The zpacing is a DicomGroup property, so we need to set it
            if not self.running:
                return False
            imagedata = vtk.vtkImageData()
            imagedata.DeepCopy(appender.GetOutput())
            spacing = imagedata.GetSpacing()

            imagedata.SetSpacing(spacing[0], spacing[1], zspacing)

        imagedata.AddObserver("ProgressEvent", lambda obj,evt:
                     update_progress(imagedata,message))
        imagedata.Update()

        return imagedata
Esempio n. 28
0
    def OpenPlistProject(self, filename):
        import invesalius.data.measures as ms
        import invesalius.data.mask as msk
        import invesalius.data.surface as srf
        
        if not const.VTK_WARNING:
            log_path = os.path.join(inv_paths.USER_LOG_DIR, 'vtkoutput.txt')
            fow = vtk.vtkFileOutputWindow()
            fow.SetFileName(log_path.encode(const.FS_ENCODE))
            ow = vtk.vtkOutputWindow()
            ow.SetInstance(fow)
            
        filelist = Extract(filename, tempfile.mkdtemp())
        dirpath = os.path.abspath(os.path.split(filelist[0])[0])

        # Opening the main file from invesalius 3 project
        main_plist =  os.path.join(dirpath ,'main.plist')
        project = plistlib.readPlist(main_plist)

        format_version = project["format_version"]
        if format_version > const.INVESALIUS_ACTUAL_FORMAT_VERSION:
            from invesalius.gui.dialogs import ImportOldFormatInvFile
            ImportOldFormatInvFile()

        # case info
        self.name = project["name"]
        self.modality = project["modality"]
        self.original_orientation = project["orientation"]
        self.window = project["window_width"]
        self.level = project["window_level"]
        self.threshold_range = project["scalar_range"]
        self.spacing = project["spacing"]
        if project.get("affine"):
            self.affine = project["affine"]
            Publisher.sendMessage('Update affine matrix',
                                  affine=self.affine, status=True)

        self.compress = project.get("compress", True)

        # Opening the matrix containing the slices
        filepath = os.path.join(dirpath, project["matrix"]["filename"])
        self.matrix_filename = filepath
        self.matrix_shape = project["matrix"]['shape']
        self.matrix_dtype = project["matrix"]['dtype']

        # Opening the masks
        self.mask_dict = {}
        for index in project["masks"]:
            filename = project["masks"][index]
            filepath = os.path.join(dirpath, filename)
            m = msk.Mask()
            m.OpenPList(filepath)
            self.mask_dict[m.index] = m

        # Opening the surfaces
        self.surface_dict = {}
        for index in project["surfaces"]:
            filename = project["surfaces"][index]
            filepath = os.path.join(dirpath, filename)
            s = srf.Surface(int(index))
            s.OpenPList(filepath)
            self.surface_dict[s.index] = s

        # Opening the measurements
        self.measurement_dict = {}
        measurements = plistlib.readPlist(os.path.join(dirpath,
                                                       project["measurements"]))
        for index in measurements:
            if measurements[index]["type"] in (const.DENSITY_ELLIPSE, const.DENSITY_POLYGON):
                measure = ms.DensityMeasurement()
            else:
                measure = ms.Measurement()
            measure.Load(measurements[index])
            self.measurement_dict[int(index)] = measure
Esempio n. 29
0
"""
from __future__ import division
import numpy as np
npl = np.linalg
from mayavi import mlab
from tvtk.tools import visual
import motion

# Send pointlessly spammed mayavi warnings to the shadow realm
import os, vtk
if os.path.exists("/dev/null"): shadow_realm = "/dev/null"
else: shadow_realm = "c:\\nul"
mlab_warning_output = vtk.vtkFileOutputWindow()
mlab_warning_output.SetFileName(shadow_realm)
vtk.vtkOutputWindow().SetInstance(mlab_warning_output)


class Viz(object):
    """
    Allows easy creation of a figure window with multicopter and environment visualization.

    model:            Model object for the multicopter
    building_layout:  array of booleans describing where buildings are in a grid
    building_size:    tuple of (length, width, height) that applies to all buildings
    building_spacing: single number for the distance between adjacent buildings
    fig:              the Mayavi figure to draw to, a new one is made if left None

    """
    def __init__(self,
                 model,
Esempio n. 30
0
    def pickOriginAndZone(self,x,y,z,substrateHeightGuess,altitude=0.001,pickZone=True):
        # dirty hack to suppress VTK errors when setting origin's mlab_data
        output=vtk.vtkFileOutputWindow()
        output.SetFileName("log.txt")
        vtk.vtkOutputWindow().SetInstance(output)          
        
        s = mlab.mesh(x, y, z)
        s.components[1].property.lighting = False
        maximumHeight = z.max()   
        safeHeight = maximumHeight+0.01
        
        origin = mlab.points3d(float(x.min()), float(y.min()), 0.0, mode='axes',
                               color=(1, 0, 0),
                               scale_factor=0.03) 
        if pickZone:
            scanZone = HorizontalRectangle((0,0,0),height=0,displayZOffset=self.calibration.mechanical.spotZ.asUnit('m'))                                              
        substrateHeightZone = HorizontalRectangle((1,0,0),height=0)

        def updateSubstrateHeight(newHeight):
            colorRangeHeight = altitude-self.calibration.mechanical.spotZ.asUnit('m')
            s.module_manager.scalar_lut_manager.data_range = (newHeight-colorRangeHeight,newHeight+colorRangeHeight)
            origin.mlab_source.set(z = newHeight)
            if pickZone:
                scanZone.height = newHeight+float(altitude)
            substrateHeightZone.height = newHeight
            
        updateSubstrateHeight(float(substrateHeightGuess))
                        
        def originSelectorCallBack(picker):
            origin.mlab_source.set(x = picker.pick_position[0],
                                   y = picker.pick_position[1])
            
            selectedPosition = Position(picker.pick_position,unit='m')
            try:
                self.setProbeLocation(Position([selectedPosition[0],selectedPosition[1],safeHeight],'m'))    
                self.setProbeLocation(selectedPosition + Position([0,0,0.002],'m'))    
            except Warning:
                pass
      
        picker = mlab.gcf().on_mouse_pick(originSelectorCallBack,
                                          type='cell',
                                          button='Middle')
            
        def zoneSelectorCallback(picker,zone):
            pickedPosition = picker.pick_position[0:2]
            if pickZone:
                self.setProbeLocation(Position([pickedPosition[0],pickedPosition[1],safeHeight],'m'))
                self.setProbeLocation(Position([pickedPosition[0],pickedPosition[1],scanZone.height],'m'))

            if picker.topRightPicked:
                zone.bottomLeft = pickedPosition
            else:
                zone.topRight = pickedPosition
            picker.topRightPicked = not(picker.topRightPicked)
        def scanZoneSelectorCallback(picker):  
            return zoneSelectorCallback(picker,scanZone)
        def substrateHeightZoneSelectorCallback(picker):
            zoneSelectorCallback(picker,substrateHeightZone)
            if not(picker.topRightPicked):
                substrateHeightZone.sort()
                zValuesInZone = z[(x > substrateHeightZone.bottomLeft[0]) &
                                  (x < substrateHeightZone.topRight[0]) &
                                  (y > substrateHeightZone.bottomLeft[1]) &
                                  (y < substrateHeightZone.topRight[1])]
                print 'Estimating substrate height based on',zValuesInZone.shape,'values...'
                if len(zValuesInZone) > 0:                
                    heightEstimate = self.estimateSubstrateHeight(zValuesInZone)
                    updateSubstrateHeight(heightEstimate)
            
            
        picker = mlab.gcf().on_mouse_pick(scanZoneSelectorCallback,
                                          type='cell',
                                          button='Right')
        picker.add_trait('topRightPicked',api.Bool(False))

        picker = mlab.gcf().on_mouse_pick(substrateHeightZoneSelectorCallback,
                                          type='cell',
                                          button='Left')
        picker.add_trait('topRightPicked',api.Bool(False))
        
        mlab.orientation_axes()
        mlab.view(azimuth=0,elevation=0)
        mlab.show()   
        
        originPosition = Position(origin.mlab_source.points[0][:],'m')  
                       
        if pickZone:
            scanZone.sort()
            lastProbeLaserPosition = self.getProbeLocation()
            lastProbeLaserPosition[2] = safeHeight
            self.setProbeLocation(lastProbeLaserPosition)                
            return (originPosition,scanZone)    
        else:
            return originPosition
Esempio n. 31
0
    def __init__(self, lattice, size, pos):
        wx.Frame.__init__(self,
                          None,
                          -1,
                          "Lattice Preview",
                          size=size,
                          pos=pos)
        self.lattice = lattice

        # menu bar
        menuBar = wx.MenuBar()
        menuFile = wx.Menu()
        menuFileAbout = menuFile.Append(-1, "About...", "About")
        menuFile.AppendSeparator()
        menuFileNew = menuFile.Append(-1, "&New...\tCtrl+N", "New Preview")
        menuFileClose = menuFile.Append(-1, "&Close\tCtrl+W", "Close Window")
        self.Bind(wx.EVT_MENU, self.ShowAbout, menuFileAbout)
        self.Bind(wx.EVT_MENU, self.OnNew, menuFileNew)
        self.Bind(wx.EVT_MENU, self.OnClose, menuFileClose)
        menuBar.Append(menuFile, "Preview")
        self.menuView = wx.Menu()
        if len(lattice.vertexTypes) > 0:
            self.menuView.Append(-1, "Vertex Type").Enable(False)
            for t in lattice.vertexTypes:
                m = self.menuView.AppendCheckItem(-1, "  " + str(t))
                m.Check(True)
                self.Bind(wx.EVT_MENU, self.OnViewVertex, m)
        if len(lattice.vertexTypes) > 0 and len(lattice.edgeTypes) > 0:
            self.menuView.AppendSeparator()
        if len(lattice.edgeTypes) > 0:
            self.menuView.Append(-1, "Edge Type").Enable(False)
            for t in lattice.edgeTypes:
                m = self.menuView.AppendCheckItem(-1, "  " + str(t))
                m.Check(True)
                self.Bind(wx.EVT_MENU, self.OnViewEdge, m)
        if len(lattice.vertexTypes) > 0 or len(lattice.edgeTypes) > 0:
            self.menuView.AppendSeparator()
            m = self.menuView.Append(-1, "Show All")
            self.Bind(wx.EVT_MENU, self.OnShowAll, m)
            m = self.menuView.Append(-1, "Hide All")
            self.Bind(wx.EVT_MENU, self.OnHideAll, m)
        menuBar.Append(self.menuView, "View")
        self.SetMenuBar(menuBar)

        main = wx.BoxSizer(wx.VERTICAL)
        self.SetBackgroundColour('#eeffff')

        self.vtkwidget = wxVTKRenderWindowInteractor(self, -1)
        main.Add(self.vtkwidget, 1, wx.EXPAND)
        self.SetSizer(main)
        self.Layout()

        self.vtkwidget.Enable(1)
        self.vtkwidget.AddObserver("ExitEvent", lambda o, e, f=self: f.Close())

        self.vertexActors = []
        self.vertexView = []
        self.edgeActors = []
        self.edgeView = []
        self.InitColors()

        self.renderer = vtk.vtkRenderer()
        self.renderer.SetBackground(0.1, 0.2, 0.4)
        self.vtkwidget.GetRenderWindow().AddRenderer(self.renderer)
        vtk.vtkOutputWindow().PromptUserOff()

        self.ShowPreview()
Esempio n. 32
0
    vtkDataReader,
    vtkXMLFileReadTester,
    vtkStringOutputWindow,
    vtkOutputWindow,
)
from ogs5py.tools.types import PCS_TYP
from ogs5py.reader.vtkhelper import vtkreader_dict, XMLreader_dict
from ogs5py.tools.output import split_ply_path, split_pnt_path, readpvd_single
from ogs5py.reader.techelper import readtec_single_table, readtec_multi_table
from ogs5py.tools.tools import split_file_path

# redirect VTK error to a string
VTK_ERR = vtkStringOutputWindow()
"""VTK Error output. Accessible with ``VTK_ERR.GetOutput()``"""

VTK_STD_OUT = vtkOutputWindow()
VTK_STD_OUT.SetInstance(VTK_ERR)


###############################################################################
# vtk readers
###############################################################################


def readvtk_single(infile):
    """Read an arbitrary vtk/vtkXML file to a dictionary wtih its data."""
    xml_checker = vtkXMLFileReadTester()
    xml_checker.SetFileName(infile)
    is_xml = bool(xml_checker.TestReadFile())
    if is_xml:
        # check for vtk-XML-type
Esempio n. 33
0
def create_surface_piece(filename, shape, dtype, mask_filename, mask_shape,
                         mask_dtype, roi, spacing, mode, min_value, max_value,
                         decimate_reduction, smooth_relaxation_factor,
                         smooth_iterations, language, flip_image,
                         from_binary, algorithm, imagedata_resolution, fill_border_holes):


    log_path = tempfile.mktemp('vtkoutput.txt')
    fow = vtk.vtkFileOutputWindow()
    fow.SetFileName(log_path)
    ow = vtk.vtkOutputWindow()
    ow.SetInstance(fow)


    pad_bottom = (roi.start == 0)
    pad_top = (roi.stop >= shape[0])

    if fill_border_holes:
        padding = (1, 1, pad_bottom)
    else:
        padding = (0, 0, 0)

    if from_binary:
        mask = numpy.memmap(mask_filename, mode='r',
                                 dtype=mask_dtype,
                                 shape=mask_shape)
        if fill_border_holes:
            a_mask = pad_image(mask[roi.start + 1: roi.stop + 1, 1:, 1:], 0, pad_bottom, pad_top)
        else:
            a_mask = numpy.array(mask[roi.start + 1: roi.stop + 1, 1:, 1:])
        image =  converters.to_vtk(a_mask, spacing, roi.start, "AXIAL", padding=padding)
        del a_mask
    else:
        image = numpy.memmap(filename, mode='r', dtype=dtype,
                                  shape=shape)
        mask = numpy.memmap(mask_filename, mode='r',
                                 dtype=mask_dtype,
                                 shape=mask_shape)
        if fill_border_holes:
            a_image = pad_image(image[roi], numpy.iinfo(image.dtype).min, pad_bottom, pad_top)
        else:
            a_image = numpy.array(image[roi])
        #  if z_iadd:
            #  a_image[0, 1:-1, 1:-1] = image[0]
        #  if z_eadd:
            #  a_image[-1, 1:-1, 1:-1] = image[-1]

        if algorithm == u'InVesalius 3.b2':
            a_mask = numpy.array(mask[roi.start + 1: roi.stop + 1, 1:, 1:])
            a_image[a_mask == 1] = a_image.min() - 1
            a_image[a_mask == 254] = (min_value + max_value) / 2.0

            image =  converters.to_vtk(a_image, spacing, roi.start, "AXIAL", padding=padding)

            gauss = vtk.vtkImageGaussianSmooth()
            gauss.SetInputData(image)
            gauss.SetRadiusFactor(0.3)
            gauss.ReleaseDataFlagOn()
            gauss.Update()

            del image
            image = gauss.GetOutput()
            del gauss
            del a_mask
        else:
            #  if z_iadd:
                #  origin = -spacing[0], -spacing[1], -spacing[2]
            #  else:
                #  origin = 0, -spacing[1], -spacing[2]
            image = converters.to_vtk(a_image, spacing, roi.start, "AXIAL", padding=padding)
        del a_image

    if imagedata_resolution:
        image = ResampleImage3D(image, imagedata_resolution)

    flip = vtk.vtkImageFlip()
    flip.SetInputData(image)
    flip.SetFilteredAxis(1)
    flip.FlipAboutOriginOn()
    flip.ReleaseDataFlagOn()
    flip.Update()

    #  writer = vtk.vtkXMLImageDataWriter()
    #  writer.SetFileName('/tmp/camboja.vti')
    #  writer.SetInputData(flip.GetOutput())
    #  writer.Write()

    del image
    image = flip.GetOutput()
    del flip

    contour = vtk.vtkContourFilter()
    contour.SetInputData(image)
    if from_binary:
        contour.SetValue(0, 127) # initial threshold
    else:
        contour.SetValue(0, min_value) # initial threshold
        contour.SetValue(1, max_value) # final threshold
    #  contour.ComputeScalarsOn()
    #  contour.ComputeGradientsOn()
    #  contour.ComputeNormalsOn()
    contour.ReleaseDataFlagOn()
    contour.Update()

    polydata = contour.GetOutput()
    del image
    del contour

    filename = tempfile.mktemp(suffix='_%d_%d.vtp' % (roi.start, roi.stop))
    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetInputData(polydata)
    writer.SetFileName(filename)
    writer.Write()

    print("Writing piece", roi, "to", filename)
    print("MY PID MC", os.getpid())
    return filename
Esempio n. 34
0
    def simulate(self,
                 q0,
                 control,
                 tN=0,
                 dt=0.005,
                 goal=None,
                 override=None,
                 Des=None):
        """
        Runs the simulation and displays / plots the results.

        q0:       array initial state condition [pos, ang1, ang2, vel, angvel1, angvel2]
        control:  function of array state, scalar time, and scalar goal that returns a scalar input force
        tN:       scalar duration in time units, set to 0 for realtime simulation
        dt:       scalar timestep for simulation
        goal:     optional scalar position to be passed to control and marked as "goal" in visualizations
        override: optional function of scalar time that returns an array state that overrides
                  the actual simulation (allows you to visualize an arbitrary trajectory)
        Des:      tuple of time and state trajectories to be plotted as desired

        """
        q0 = np.array(q0, dtype=np.float64)

        # Positive tN means timeseries simulation
        if tN > 0:
            from matplotlib import pyplot

            # Record real start time
            print "----"
            print "Simulating acrocart for a horizon of {}...".format(tN)
            start_time = time.time()

            # Run timeseries simulation and store results
            T = np.arange(0, tN + dt, dt)
            Q = np.zeros((len(T), self.dyn.n_q), dtype=np.float64)
            U = np.zeros((len(T), self.dyn.n_u), dtype=np.float64)
            Q[0] = np.copy(q0)
            for i, t in enumerate(T[:-1]):
                U[i] = control(Q[i], t, goal)
                if override is None:
                    Q[i + 1] = self.dyn.step(Q[i], U[i], dt)
                else:
                    Q[i + 1] = override(t)
            print "Simulation finished in {} realtime seconds.".format(
                np.round(time.time() - start_time, 3))
            print "Final state: {}".format(np.round(Q[-1], 3))
            print "Sum of squared input forces: {}".format(
                np.round(np.sum(U[:, 0]**2), 3))

            # Plot results
            print "Plotting results... (close plots to continue)"
            print "----"
            fig = pyplot.figure()
            fig.suptitle("AcroCart Simulation", fontsize=24)
            ax = fig.add_subplot(2, 1, 1)
            ax.plot(T, Q[:, 0], "k", label="pos")
            ax.plot(T, Q[:, 1], "g", label="ang1")
            ax.plot(T, Q[:, 2], "b", label="ang2")
            if Des is not None:
                ax.plot(Des[0], Des[1][:, 0], "k--")
                ax.plot(Des[0], Des[1][:, 1], "g--")
                ax.plot(Des[0], Des[1][:, 2], "b--")
            ax.set_xlim([T[0], T[-1]])
            ax.legend(fontsize=16)
            ax.set_ylabel("Pose", fontsize=16)
            ax.grid(True)
            ax = fig.add_subplot(2, 1, 2)
            ax.plot(T, U[:, 0], "r", label="input")
            ax.set_xlim([T[0], T[-1]])
            ax.set_ylabel("Input", fontsize=16)
            ax.set_xlabel("Time", fontsize=16)
            ax.grid(True)
            pyplot.show()  # blocking

        # Nonpositive tN implies realtime simulation
        else:
            print "----"
            print "Starting realtime acrocart simulation..."
            print "Setting-up Mayavi graphics..."
            from mayavi import mlab
            import os, vtk
            if os.path.exists("/dev/null"): shadow_realm = "/dev/null"
            else: shadow_realm = "c:\\nul"
            mlab_warning_output = vtk.vtkFileOutputWindow()
            mlab_warning_output.SetFileName(shadow_realm)
            vtk.vtkOutputWindow().SetInstance(mlab_warning_output)

            # Generate visualization objects and initial figure view
            fig = mlab.figure(size=(500, 500), bgcolor=(0.25, 0.25, 0.25))
            rail = mlab.plot3d(self.dyn.rail_lims, (0, 0), (0, 0),
                               line_width=1,
                               color=(1, 1, 1))
            cart = mlab.points3d(q0[0],
                                 0,
                                 0,
                                 scale_factor=0.2,
                                 mode="cube",
                                 color=(0, 0, 1))
            joint1 = mlab.points3d(q0[0],
                                   -0.125,
                                   0,
                                   scale_factor=0.12,
                                   color=(0, 1, 1))
            x1, y1 = q0[0] + self.dyn.l1 * np.sin(
                q0[1]), -self.dyn.l1 * np.cos(q0[1])
            pole1 = mlab.plot3d((q0[0], x1), (-0.15, -0.15), (0, y1),
                                line_width=1,
                                color=(0, 1, 0))
            joint2 = mlab.points3d(x1,
                                   -0.175,
                                   y1,
                                   scale_factor=0.12,
                                   color=(0, 1, 1))
            pole2 = mlab.plot3d((x1, x1 + self.dyn.l2 * np.sin(q0[2])),
                                (-0.2, -0.2),
                                (y1, y1 - self.dyn.l2 * np.cos(q0[2])),
                                line_width=1,
                                color=(1, 0, 0))
            disp = mlab.text3d(-0.6,
                               0,
                               1.2 * (self.dyn.l1 + self.dyn.l2),
                               "t = 0.0",
                               scale=0.45)
            if goal is not None:
                mlab.points3d(goal,
                              0,
                              -1.2 * (self.dyn.l1 + self.dyn.l2),
                              scale_factor=0.2,
                              mode="axes",
                              color=(1, 0, 0))
            recenter = lambda: mlab.view(
                azimuth=-90,
                elevation=90,
                focalpoint=(np.mean(self.dyn.rail_lims), 0, 0),
                distance=1.8 * np.sum(np.abs(self.dyn.rail_lims)))
            recenter()

            # Setup user keyboard interactions
            disturb = [0.0]
            reset = [False]

            def keyPressEvent(event):
                k = str(event.text())
                if k == '.': disturb[0] += 0.5
                elif k == ',': disturb[0] -= 0.5
                elif k == ' ': disturb[0] = 0.0
                elif k == 'v': recenter()
                elif k == 'r':
                    t[0] = 0.0
                    q[0] = np.copy(q0)
                    disturb[0] = 0.0
                    print "User triggered reset!"
                    reset[0] = True
                    start_time[0] = time.time()

            fig.scene._vtk_control.keyPressEvent = keyPressEvent
            print "--\nUSER KEYBOARD CONTROLS:"
            if override is None:
                print "Increment / decrement disturbance cart-force with '>' / '<' and cancel disturbance with ' ' (spacebar)."
            print "Reset view with 'v'. Reset simulation with 'r'.\n--"
            print "(close all Mayavi windows to continue...)"

            # Wrap simulation in animation
            @mlab.animate(delay=50)  # 20 FPS is best Mayavi can do
            def realtime_loop():
                while True:

                    # Simulate physics up to realtime
                    while (t[0] <
                           time.time() - start_time[0]) and not reset[0]:
                        if override is None:
                            q[0] = self.dyn.step(q[0],
                                                 control(q[0], t[0],
                                                         goal), dt, disturb[0])
                        else:
                            q[0] = override(t[0])
                        t[0] += dt

                    # Update animation
                    reset[0] = False
                    cart.mlab_source.set(x=q[0][0])
                    joint1.mlab_source.set(x=q[0][0])
                    x1, y1 = q[0][0] + self.dyn.l1 * np.sin(
                        q[0][1]), -self.dyn.l1 * np.cos(q[0][1])
                    pole1.mlab_source.set(x=(q[0][0], x1), z=(0, y1))
                    joint2.mlab_source.set(x=x1, z=y1)
                    pole2.mlab_source.set(
                        x=(x1, x1 + self.dyn.l2 * np.sin(q[0][2])),
                        z=(y1, y1 - self.dyn.l2 * np.cos(q[0][2])))
                    disp.text = "t = " + str(np.round(t[0], 1))
                    yield

            # Begin simulation and visualization
            t = [0.0]
            q = [np.copy(q0)]
            start_time = [time.time()]
            realtime_loop()
            mlab.show()  # blocking
            print "----"
Esempio n. 35
0
import sys
import os
import vtk
import igl
from vtk.util import numpy_support
import numpy as np
import math
import random
from scipy.sparse import csr_matrix, coo_matrix

vtk_out = vtk.vtkOutputWindow()
vtk_out.SetInstance(vtk_out)

#Make Shader

rootPath = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(rootPath, "shaders", "normalmap.glsl"),
          'r') as shaderFile:
    FragmentShaderText = shaderFile.read()

with open(os.path.join(rootPath, "shaders", "vertexShader.glsl"),
          'r') as shaderFile:
    VertexShaderText = shaderFile.read()


def tutte(V, F):

    #Get Boundary and Edge
    L = igl.boundary_loop(F)
    sizeL = len(L)
Esempio n. 36
0
def join_process_surface(filenames, algorithm, smooth_iterations, smooth_relaxation_factor, decimate_reduction, keep_largest, fill_holes, options, msg_queue):
    def send_message(msg):
        try:
            msg_queue.put_nowait(msg)
        except queue.Full as e:
            print(e)

    log_path = tempfile.mktemp('vtkoutput.txt')
    fow = vtk.vtkFileOutputWindow()
    fow.SetFileName(log_path)
    ow = vtk.vtkOutputWindow()
    ow.SetInstance(fow)

    send_message('Joining surfaces ...')
    polydata_append = vtk.vtkAppendPolyData()
    for f in filenames:
        reader = vtk.vtkXMLPolyDataReader()
        reader.SetFileName(f)
        reader.Update()

        polydata = reader.GetOutput()

        polydata_append.AddInputData(polydata)
        del reader
        del polydata

    polydata_append.Update()
    #  polydata_append.GetOutput().ReleaseDataFlagOn()
    polydata = polydata_append.GetOutput()
    #polydata.Register(None)
    #  polydata.SetSource(None)
    del polydata_append

    send_message('Cleaning surface ...')
    clean = vtk.vtkCleanPolyData()
    #  clean.ReleaseDataFlagOn()
    #  clean.GetOutput().ReleaseDataFlagOn()
    clean_ref = weakref.ref(clean)
    #  clean_ref().AddObserver("ProgressEvent", lambda obj,evt:
                    #  UpdateProgress(clean_ref(), _("Creating 3D surface...")))
    clean.SetInputData(polydata)
    clean.PointMergingOn()
    clean.Update()

    del polydata
    polydata = clean.GetOutput()
    #  polydata.SetSource(None)
    del clean

    if algorithm == 'ca_smoothing':
        send_message('Calculating normals ...')
        normals = vtk.vtkPolyDataNormals()
        normals_ref = weakref.ref(normals)
        #  normals_ref().AddObserver("ProgressEvent", lambda obj,evt:
                                  #  UpdateProgress(normals_ref(), _("Creating 3D surface...")))
        normals.SetInputData(polydata)
        #  normals.ReleaseDataFlagOn()
        #normals.SetFeatureAngle(80)
        #normals.AutoOrientNormalsOn()
        normals.ComputeCellNormalsOn()
        #  normals.GetOutput().ReleaseDataFlagOn()
        normals.Update()
        del polydata
        polydata = normals.GetOutput()
        #  polydata.SetSource(None)
        del normals

        clean = vtk.vtkCleanPolyData()
        #  clean.ReleaseDataFlagOn()
        #  clean.GetOutput().ReleaseDataFlagOn()
        clean_ref = weakref.ref(clean)
        #  clean_ref().AddObserver("ProgressEvent", lambda obj,evt:
                        #  UpdateProgress(clean_ref(), _("Creating 3D surface...")))
        clean.SetInputData(polydata)
        clean.PointMergingOn()
        clean.Update()

        del polydata
        polydata = clean.GetOutput()
        #  polydata.SetSource(None)
        del clean

        #  try:
            #  polydata.BuildLinks()
        #  except TypeError:
            #  polydata.BuildLinks(0)
        #  polydata = ca_smoothing.ca_smoothing(polydata, options['angle'],
                                             #  options['max distance'],
                                             #  options['min weight'],
                                             #  options['steps'])

        send_message('Context Aware smoothing ...')
        mesh = cy_mesh.Mesh(polydata)
        cy_mesh.ca_smoothing(mesh, options['angle'],
                             options['max distance'],
                             options['min weight'],
                             options['steps'])
        #  polydata = mesh.to_vtk()

        #  polydata.SetSource(None)
        #  polydata.DebugOn()
    #  else:
        #  #smoother = vtk.vtkWindowedSincPolyDataFilter()
        #  send_message('Smoothing ...')
        #  smoother = vtk.vtkSmoothPolyDataFilter()
        #  smoother_ref = weakref.ref(smoother)
        #  #  smoother_ref().AddObserver("ProgressEvent", lambda obj,evt:
                        #  #  UpdateProgress(smoother_ref(), _("Creating 3D surface...")))
        #  smoother.SetInputData(polydata)
        #  smoother.SetNumberOfIterations(smooth_iterations)
        #  smoother.SetRelaxationFactor(smooth_relaxation_factor)
        #  smoother.SetFeatureAngle(80)
        #  #smoother.SetEdgeAngle(90.0)
        #  #smoother.SetPassBand(0.1)
        #  smoother.BoundarySmoothingOn()
        #  smoother.FeatureEdgeSmoothingOn()
        #  #smoother.NormalizeCoordinatesOn()
        #  #smoother.NonManifoldSmoothingOn()
        #  #  smoother.ReleaseDataFlagOn()
        #  #  smoother.GetOutput().ReleaseDataFlagOn()
        #  smoother.Update()
        #  del polydata
        #  polydata = smoother.GetOutput()
        #  #polydata.Register(None)
        #  #  polydata.SetSource(None)
        #  del smoother


    if not decimate_reduction:
        print("Decimating", decimate_reduction)
        send_message('Decimating ...')
        decimation = vtk.vtkQuadricDecimation()
        #  decimation.ReleaseDataFlagOn()
        decimation.SetInputData(polydata)
        decimation.SetTargetReduction(decimate_reduction)
        decimation_ref = weakref.ref(decimation)
        #  decimation_ref().AddObserver("ProgressEvent", lambda obj,evt:
                        #  UpdateProgress(decimation_ref(), _("Creating 3D surface...")))
        #decimation.PreserveTopologyOn()
        #decimation.SplittingOff()
        #decimation.BoundaryVertexDeletionOff()
        #  decimation.GetOutput().ReleaseDataFlagOn()
        decimation.Update()
        del polydata
        polydata = decimation.GetOutput()
        #polydata.Register(None)
        #  polydata.SetSource(None)
        del decimation

    #to_measure.Register(None)
    #  to_measure.SetSource(None)

    if keep_largest:
        send_message('Finding the largest ...')
        conn = vtk.vtkPolyDataConnectivityFilter()
        conn.SetInputData(polydata)
        conn.SetExtractionModeToLargestRegion()
        conn_ref = weakref.ref(conn)
        #  conn_ref().AddObserver("ProgressEvent", lambda obj,evt:
                #  UpdateProgress(conn_ref(), _("Creating 3D surface...")))
        conn.Update()
        #  conn.GetOutput().ReleaseDataFlagOn()
        del polydata
        polydata = conn.GetOutput()
        #polydata.Register(None)
        #  polydata.SetSource(None)
        del conn

    #Filter used to detect and fill holes. Only fill boundary edges holes.
    #TODO: Hey! This piece of code is the same from
    #polydata_utils.FillSurfaceHole, we need to review this.
    if fill_holes:
        send_message('Filling holes ...')
        filled_polydata = vtk.vtkFillHolesFilter()
        #  filled_polydata.ReleaseDataFlagOn()
        filled_polydata.SetInputData(polydata)
        filled_polydata.SetHoleSize(300)
        filled_polydata_ref = weakref.ref(filled_polydata)
        #  filled_polydata_ref().AddObserver("ProgressEvent", lambda obj,evt:
                #  UpdateProgress(filled_polydata_ref(), _("Creating 3D surface...")))
        filled_polydata.Update()
        #  filled_polydata.GetOutput().ReleaseDataFlagOn()
        del polydata
        polydata = filled_polydata.GetOutput()
        #polydata.Register(None)
        #  polydata.SetSource(None)
        #  polydata.DebugOn()
        del filled_polydata

    to_measure = polydata

    normals = vtk.vtkPolyDataNormals()
    #  normals.ReleaseDataFlagOn()
    #  normals_ref = weakref.ref(normals)
    #  normals_ref().AddObserver("ProgressEvent", lambda obj,evt:
                    #  UpdateProgress(normals_ref(), _("Creating 3D surface...")))
    normals.SetInputData(polydata)
    normals.SetFeatureAngle(80)
    normals.SplittingOn()
    normals.AutoOrientNormalsOn()
    normals.NonManifoldTraversalOn()
    normals.ComputeCellNormalsOn()
    #  normals.GetOutput().ReleaseDataFlagOn()
    normals.Update()
    del polydata
    polydata = normals.GetOutput()
    #polydata.Register(None)
    #  polydata.SetSource(None)
    del normals


    #  # Improve performance
    #  stripper = vtk.vtkStripper()
    #  #  stripper.ReleaseDataFlagOn()
    #  #  stripper_ref = weakref.ref(stripper)
    #  #  stripper_ref().AddObserver("ProgressEvent", lambda obj,evt:
                    #  #  UpdateProgress(stripper_ref(), _("Creating 3D surface...")))
    #  stripper.SetInputData(polydata)
    #  stripper.PassThroughCellIdsOn()
    #  stripper.PassThroughPointIdsOn()
    #  #  stripper.GetOutput().ReleaseDataFlagOn()
    #  stripper.Update()
    #  del polydata
    #  polydata = stripper.GetOutput()
    #  #polydata.Register(None)
    #  #  polydata.SetSource(None)
    #  del stripper

    send_message('Calculating area and volume ...')
    measured_polydata = vtk.vtkMassProperties()
    measured_polydata.SetInputData(to_measure)
    measured_polydata.Update()
    volume =  float(measured_polydata.GetVolume())
    area =  float(measured_polydata.GetSurfaceArea())
    del measured_polydata

    filename = tempfile.mktemp(suffix='_full.vtp')
    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetInputData(polydata)
    writer.SetFileName(filename)
    writer.Write()
    del writer

    print("MY PID", os.getpid())
    return filename, {'volume': volume, 'area': area}
- Read in XYZ point cloud mesh
- Read in Scalar values and apply a single one
- Create mesh from delaunay
- Export to VTK format for visualisation in Paraview

Updates:
- Read all 3 velocities in as a vector and apply to dataset (SetVectors?)
"""

# This example shows how to use Delaunay3D with alpha shapes.
import vtk
from vtk import *

# prevent error window from popping up
ow = vtk.vtkOutputWindow()
ow.DebugOff()
ow.GlobalWarningDisplayOff()

# flags
large = 1
subsamp = 0

if (large == 1):
    filename = 'GT_3d.csv'
    Name = 'Vol'
    cols = [0, 1, 2, 3, 4, 5]
else:
    filename = 'grid_vels.csv'
    Name = 'Surf'
    cols = [1, 2, 3, 4, 5, 6]
 def setup_vtk_log(log_file: str = "vtk.log", append: bool = False):
     fow = vtk.vtkFileOutputWindow()
     fow.SetFileName(os.path.join(os.path.dirname(__file__), log_file))
     fow.SetAppend(append)
     ow = vtk.vtkOutputWindow()
     ow.SetInstance(fow)
Esempio n. 39
0
    def CreateImageData(self, filelist, zspacing, size, bits):
        message = _("Generating multiplanar visualization...")

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

        x, y = size
        px, py = utils.predict_memory(len(filelist), x, y, bits)
        utils.debug("Image Resized to >>> %f x %f" % (px, py))

        if (x == px) and (y == py):
            const.REDUCE_IMAGEDATA_QUALITY = 0
        else:
            const.REDUCE_IMAGEDATA_QUALITY = 1

        if not (const.REDUCE_IMAGEDATA_QUALITY):
            update_progress = vtk_utils.ShowProgress(
                1, dialog_type="ProgressDialog")

            array = vtk.vtkStringArray()
            for x in xrange(len(filelist)):
                if not self.running:
                    return False
                array.InsertValue(x, filelist[x])

            if not self.running:
                return False
            reader = vtkgdcm.vtkGDCMImageReader()
            reader.SetFileNames(array)
            reader.AddObserver(
                "ProgressEvent",
                lambda obj, evt: update_progress(reader, message))
            reader.Update()

            if not self.running:
                reader.AbortExecuteOn()
                return False
            # The zpacing is a DicomGroup property, so we need to set it
            imagedata = vtk.vtkImageData()
            imagedata.DeepCopy(reader.GetOutput())
            spacing = imagedata.GetSpacing()
            imagedata.SetSpacing(spacing[0], spacing[1], zspacing)
        else:

            update_progress = vtk_utils.ShowProgress(
                2 * len(filelist), dialog_type="ProgressDialog")

            # Reformat each slice and future append them
            appender = vtk.vtkImageAppend()
            appender.SetAppendAxis(2)  #Define Stack in Z

            # Reformat each slice
            for x in xrange(len(filelist)):
                # TODO: We need to check this automatically according
                # to each computer's architecture
                # If the resolution of the matrix is too large
                if not self.running:
                    return False
                reader = vtkgdcm.vtkGDCMImageReader()
                reader.SetFileName(filelist[x])
                reader.AddObserver(
                    "ProgressEvent",
                    lambda obj, evt: update_progress(reader, message))
                reader.Update()

                #Resample image in x,y dimension
                slice_imagedata = ResampleImage2D(reader.GetOutput(), px, py,
                                                  update_progress)
                #Stack images in Z axes
                appender.AddInput(slice_imagedata)
                #appender.AddObserver("ProgressEvent", lambda obj,evt:update_progress(appender))
                appender.Update()

            # The zpacing is a DicomGroup property, so we need to set it
            if not self.running:
                return False
            imagedata = vtk.vtkImageData()
            imagedata.DeepCopy(appender.GetOutput())
            spacing = imagedata.GetSpacing()

            imagedata.SetSpacing(spacing[0], spacing[1], zspacing)

        imagedata.AddObserver(
            "ProgressEvent",
            lambda obj, evt: update_progress(imagedata, message))
        imagedata.Update()

        return imagedata
import vtk

# from vtk.util.misc import vtkGetDataRoot
# from vtk.util.misc import vtkGetTempDir
import sys
# import os
# VTK_DATA_ROOT = vtkGetDataRoot()
# VTK_TEMP_DIR = vtkGetTempDir()

output = vtk.vtkFileOutputWindow()
output.SetFileName("log.txt")
vtk.vtkOutputWindow().SetInstance(output)

test_files = [['minimal.nii.gz', 'out_minimal.nii.gz']]

display_file = 'data/flair.nii.gz'


def TestDisplay(file):
    # in_path = os.path.join(str(VTK_DATA_ROOT), "Data", file)
    in_path = "./data/flair.nii.gz"
    reader = vtk.vtkNIFTIImageReader()
    reader.SetFileName(in_path)
    reader.Update()

    # # marching cubes?
    # contour = vtk.vtkMarchingCubes()
    # contour.SetInput(brain_reader.GetOutput())
    # contour.Update()
    #
    # mapper = vtk.vtkImageSliceMapper()
Esempio n. 41
0
        del self.vtk_widget_3
        del self.vtk_widget_4
        
        self.vtk_widget_2 = VTK_Widget2(0)
        self.vtk_widget_3 = VTK_Widget2(1)
        self.vtk_widget_4 = VTK_Widget2(2)
        self.vtk_widget_1 = VTK_Widget1()
        
        self.HSplitterTop.addWidget(self.vtk_widget_1)
        self.HSplitterTop.addWidget(self.vtk_widget_2)
        self.HSplitterBottom.addWidget(self.vtk_widget_3)
        self.HSplitterBottom.addWidget(self.vtk_widget_4)
        self.vtk_widget_1.SetSource(self.reader.GetOutput())
        self.vtk_widget_2.SetSource(self.reader.GetOutput())
        self.vtk_widget_3.SetSource(self.reader.GetOutput())
        self.vtk_widget_4.SetSource(self.reader.GetOutput())
        
                    
# START APPLICATION    
app = QApplication(sys.argv)

ow = vtk.vtkOutputWindow()
ow.SetGlobalWarningDisplay(0)

mainwindow = MainVizWindow()
mainwindow.show()
if sys.argv.__len__() > 1:
    source = sys.argv[1]
    mainwindow.setSource(source)
sys.exit(app.exec_())
Esempio n. 42
0
#!/usr/bin/python

from __future__ import division
import traits
import traitsui
from mayavi import mlab
import cv2
import numpy as np
import vtk

output = vtk.vtkFileOutputWindow()
# Throw the stupid vtk runtime errors into a burning pit
output.SetFileName("/dev/null")
vtk.vtkOutputWindow().SetInstance(output)

color_ranges = {
    'hsv': np.array([
        [0, 179],  # Stupid OpenCV saving 1 bit...
        [0, 255],
        [0, 255]
    ]),
    'bgr': np.array([
        [0, 255],
        [0, 255],
        [0, 255]
    ])
}


def np_inrange(vector, lower_range, upper_range):
    sat_lower = np.min(vector > lower_range, axis=1)
Esempio n. 43
0
        self.tabs.tabBar().setTabButton(1, QTabBar.RightSide, None)
        self.tabs.addTab(self.tab_gad, icon_tab_loc, "Locate(GAD)")
        self.tabs.tabBar().setTabButton(2, QTabBar.RightSide, None)
        self.tabs.addTab(self.tab_jhd, icon_tab_rel, "Relocate(JHD)")
        self.tabs.tabBar().setTabButton(3, QTabBar.RightSide, None)
        self.tabs.addTab(self.tab_hdd, icon_tab_rel, "Relocate(DD)")
        self.tabs.tabBar().setTabButton(4, QTabBar.RightSide, None)
        self.tabs.addTab(self.tab_tg, icon_tab_tg, "Tomography")
        self.tabs.tabBar().setTabButton(5, QTabBar.RightSide, None)

        self.setCentralWidget(self.tabs)

    def closeTab (self, currentIndex):
        currentQWidget = self.tabs.widget(currentIndex)
        currentQWidget.deleteLater()
        self.tabs.removeTab(currentIndex)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = MainWindow()
    splash_pix = QPixmap(splash_screen)
    splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
    splash.show()
    time.sleep(1)
    splash.close()
    main.showMaximized()
    errOut = vtk.vtkFileOutputWindow()
    errOut.SetFileName(os.path.join(os.getcwd(),'bug','vtk.bug'))
    vtkStdErrOut = vtk.vtkOutputWindow()
    vtkStdErrOut.SetInstance(errOut)
    sys.exit(app.exec_())
Esempio n. 44
0
    def OpenPlistProject(self, filename):
        import invesalius.data.measures as ms
        import invesalius.data.mask as msk
        import invesalius.data.surface as srf
        
        if not const.VTK_WARNING:
            log_path = os.path.join(const.USER_LOG_DIR, 'vtkoutput.txt')
            fow = vtk.vtkFileOutputWindow()
            fow.SetFileName(log_path.encode(const.FS_ENCODE))
            ow = vtk.vtkOutputWindow()
            ow.SetInstance(fow)
            
        filelist = Extract(filename, tempfile.mkdtemp())
        dirpath = os.path.abspath(os.path.split(filelist[0])[0])

        # Opening the main file from invesalius 3 project
        main_plist =  os.path.join(dirpath ,'main.plist')
        project = plistlib.readPlist(main_plist)

        format_version = project["format_version"]
        if format_version > const.INVESALIUS_ACTUAL_FORMAT_VERSION:
            from invesalius.gui.dialogs import ImportOldFormatInvFile
            ImportOldFormatInvFile()

        # case info
        self.name = project["name"]
        self.modality = project["modality"]
        self.original_orientation = project["orientation"]
        self.window = project["window_width"]
        self.level = project["window_level"]
        self.threshold_range = project["scalar_range"]
        self.spacing = project["spacing"]
        if project.get("affine"):
            self.affine = project["affine"]
            Publisher.sendMessage('Update affine matrix',
                                  affine=self.affine, status=True)

        self.compress = project.get("compress", True)

        # Opening the matrix containing the slices
        filepath = os.path.join(dirpath, project["matrix"]["filename"])
        self.matrix_filename = filepath
        self.matrix_shape = project["matrix"]['shape']
        self.matrix_dtype = project["matrix"]['dtype']

        # Opening the masks
        self.mask_dict = {}
        for index in project["masks"]:
            filename = project["masks"][index]
            filepath = os.path.join(dirpath, filename)
            m = msk.Mask()
            m.OpenPList(filepath)
            self.mask_dict[m.index] = m

        # Opening the surfaces
        self.surface_dict = {}
        for index in project["surfaces"]:
            filename = project["surfaces"][index]
            filepath = os.path.join(dirpath, filename)
            s = srf.Surface(int(index))
            s.OpenPList(filepath)
            self.surface_dict[s.index] = s

        # Opening the measurements
        self.measurement_dict = {}
        measurements = plistlib.readPlist(os.path.join(dirpath,
                                                       project["measurements"]))
        for index in measurements:
            if measurements[index]["type"] in (const.DENSITY_ELLIPSE, const.DENSITY_POLYGON):
                measure = ms.DensityMeasurement()
            else:
                measure = ms.Measurement()
            measure.Load(measurements[index])
            self.measurement_dict[int(index)] = measure