Example #1
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])
Example #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.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
Example #3
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   
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
Example #5
0
    def __init__(self):
        # Dynamically altered data
        self.poly_data = []
        self.bar_data  = []

        # Static poly data
        self.resize_factor = []

        # Mappers for rendering
        self.poly_mappers = []
        self.line_mappers = []
        self.text_mappers = []
        self.bar_mappers  = []

        # Actor objects
        self.actors = []
        self.dynamic_actors = [[], []]

        # Actor Properties
        self.edge_colours = []
        self.node_ids     = []

        # TODO: Make layout grids an enumeration. (2011-08-09)
        self.layout_grid = [
            [  0.0,   0.0,  0.0],
            [  0.0,  40.0,  0.0],
            [-30.0, -30.0,  0.0],
            [ 30.0, -30.0,  0.0],
            [ 40.0,  20.0,  0.0],
            [-40.0,  20.0,  0.0]
        ]

        # Data
        self.data = []
        self.updated = False

        # Broadcast sources
        self.broadcasters = []

        # Other Attributes
        self.node_layout_strategy = None
        self.edge_layout_strategy = None
        self.text_layout_strategy = None

        # Get rid of pointless warnings
        out = vtkFileOutputWindow()
        out.SetFileName(".vtkMessageLog.log")
        vtkOutputWindow.SetInstance(out)

        # Initialize window
        self.renderer = vtkRenderer()
        self.renderer.SetBackground(1.0, 1.0, 1.0)

        self.window = vtkRenderWindow()
        self.window.AddRenderer(self.renderer)
        self.window.SetSize(600, 600)

        self.interactor = vtkRenderWindowInteractor()
        self.interactor.SetRenderWindow(self.window)
Example #6
0
def RedirectVTKMessages():
    """ Can be used to redirect VTK related error messages to a
    file."""
    log = vtk.vtkFileOutputWindow()
    log.SetFlush(1)
    log.AppendOff()
    log.SetFileName('TestEmptyInput-err.log')
    log.SetInstance(log)
Example #7
0
def main():
    err = vtk.vtkFileOutputWindow()
    err.SetFileName("viewer.log")
    vtk.vtkOutputWindow.SetInstance(err)
    
    App = QApplication(sys.argv)
    gui = Window()
    sys.exit(App.exec_())
Example #8
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
def set_vtk_log():
    import os
    import vtk
    log_path = os.path.join("vtk_log.txt")
    fow = vtk.vtkFileOutputWindow()
    fow.SetFileName(log_path)
    ow = vtk.vtkOutputWindow()
    ow.SetInstance(fow)
Example #10
0
def RedirectVTKMessages():
    """ Can be used to redirect VTK related error messages to a
    file."""
    log = vtk.vtkFileOutputWindow()
    log.SetFlush(1)
    log.AppendOff()
    log.SetFileName('TestEmptyInput-err.log')
    log.SetInstance(log)
Example #11
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
Example #12
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())
        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
Example #13
0
def redirect_vtk_messages():
    """ Redirect VTK related error messages to a file."""
    import tempfile
    tempfile.template = 'vtk-err'
    f = tempfile.mktemp('.log')
    log = vtk.vtkFileOutputWindow()
    log.SetFlush(1)
    log.SetFileName(f)
    log.SetInstance(log)
Example #14
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)
Example #15
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)
Example #16
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
Example #17
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)
Example #18
0
File: app.py Project: 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)
Example #19
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
Example #20
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)
Example #21
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)
Example #22
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
Example #23
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
    def __init__(self, filename='h_case06.vtk', to_polydata=False):

        self.filename, self.input_type = filename.split('.')
        print(self.filename)

        # Initialize log of mesh manipulations
        w = vtk.vtkFileOutputWindow()
        w.SetFileName(self.filename.split('/')[0] + '/errors.txt')
        vtk.vtkOutputWindow.SetInstance(w)

        print('Reading the data from {}.{}...'.format(self.filename,
                                                      self.input_type))
        if self.input_type == 'obj':
            self.mesh, self.scalar_range = self.read_obj()
        elif self.input_type == 'vtp':
            self.mesh, self.scalar_range = self.read_vtp()
        else:
            self.mesh, self.scalar_range = self.read_vtk(to_polydata)

        self.center_of_model = self.get_center(self.mesh)
        print('Model centered at: {}'.format(self.center_of_model))
        self.label = 0
Example #25
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])
    def __init__(self, filename='h_case06.vtk', to_polydata=False):

        self.filename, self.input_type = filename.split('.')
        print(self.filename)
        # Write vtk output to a file
        w = vtk.vtkFileOutputWindow()
        w.SetFileName(self.filename.split('/')[0] + '/errors.txt')
        vtk.vtkOutputWindow.SetInstance(w)

        print('Reading the data from {}.{}...'.format(self.filename,
                                                      self.input_type))
        if self.input_type == 'obj':
            self.mesh, self.scalar_range = self.read_obj()
        elif self.input_type == 'vtp':
            self.mesh, self.scalar_range = self.read_vtp()
        else:
            self.mesh, self.scalar_range = self.read_vtk(to_polydata)

        # self.scalar_range = [1.0, 17.0]  # Added for particular case of CT meshes
        # print('Corrected scalar range: {}'.format(self.scalar_range))
        self.center_of_heart = self.get_center(self.mesh)
        print('Model centered at: {}'.format(self.center_of_heart))
        self.label = 0
Example #27
0
    def GetDicomGroups(self, path, recursive):

        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)

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

        #Is necessary in the case user cancel
        #the load, ensure that dicomdialog is closed
        if (self.stoped):
            self.UpdateLoadFileProgress(None)
            self.stoped = False
Example #28
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.LOG_FOLDER, 'vtkoutput.txt')
        fow = vtk.vtkFileOutputWindow()
        fow.SetFileName(log_path)
        ow = vtk.vtkOutputWindow()
        ow.SetInstance(fow)

    imagedata = nib.squeeze_image(nib.load(dir_))
    imagedata = nib.as_closest_canonical(imagedata)
    imagedata.update_header()

    return imagedata
Example #29
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
Example #30
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
Example #31
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}
Example #32
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 "----"
Example #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
Example #34
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}
#!/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)
Example #36
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_())
        self.sliderWidget.setMinimum(self.viewer.GetSliceMin())
        mid = (self.viewer.GetSliceMax() - self.viewer.GetSliceMin()) / 2
        self.sliderWidget.setValue(mid)

    # signal and slot
    def slider_changed(self):
        self.viewer.SetSlice(self.sliderWidget.value())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    # raise the error log
    log_file = 'log.txt'
    with open(log_file, 'wb') as f:
        f.truncate()
    file_output_window = vtk.vtkFileOutputWindow()
    file_output_window.SetFileName(log_file)
    vtk.vtkFileOutputWindow.SetInstance(file_output_window)
    # 'coronal': 0,
    # 'sagittal': 1,
    # 'transverse': 2
    SingleView = QSliceViewWidget(orientation='coronal')
    file_name = "test_data.nii.gz"
    reader = vtk.vtkNIFTIImageReader()
    reader.SetFileName(file_name)
    reader.Update()

    SingleView.set_data_reader(reader)
    SingleView.start_render()
    SingleView.resize(QSize(800, 600))
    SingleView.show()
 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)
Example #39
0
def vtkerror(path):
    """Write VTK error window text to file at specified path."""
    err = vtk.vtkFileOutputWindow()
    err.SetFileName(path)
    err.SetInstance(err)
Example #40
0
    sudo apt-get install libqt4-svg
    sudo pip install mayavi pyside

"""
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

    """
Example #41
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
Example #42
0
import os, os.path
import sys
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# List of types and corresponding file extensions.
types = [[ 'ImageData', 'vti'],
         ['RectilinearGrid', 'vtr'],
         ['StructuredGrid', 'vts'],
         ['PolyData', 'vtp'],
         ['UnstructuredGrid', 'vtu']]

# We intentionally cause vtkErrorMacro calls to be made below.  Dump
# errors to a file to prevent a window from coming up.
fow = vtk.vtkFileOutputWindow()
fow.SetFileName("TestEmptyXMLErrors.txt")
fow.SetFlush(0)
fow.SetInstance(fow)

# Loguru will still send messages to stderr. Disable that.
vtk.vtkLogger.SetStderrVerbosity(vtk.vtkLogger.VERBOSITY_OFF)

# Prepare some test files.
f = open('emptyFile.vtk', 'wt')
f.close()
f = open('junkFile.vtk', 'wt')
f.write("v9np7598mapwcawoiur-,rjpmW9MJV28nun-q38ynq-9.8ugujqvt-8n3-nv8")
f.close()

# Test each writer/reader.
Example #43
0
 def init(cls):
     cls._current_document = Document()
     log = vtk.vtkFileOutputWindow()  #para guardar los mensajes de vtk
     log.SetFileName("logs/vtk.log")  #fichero donde se guardan
     log.SetInstance(log)  #usar este fichero
    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
Example #45
0
import os
import sys
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# List of types and corresponding file extensions.
types = [[ 'ImageData', 'vti'],
         ['RectilinearGrid', 'vtr'],
         ['StructuredGrid', 'vts'],
         ['PolyData', 'vtp'],
         ['UnstructuredGrid', 'vtu']]

# We intentionally cause vtkErrorMacro calls to be made below.  Dump
# errors to a file to prevent a window from coming up.
fow = vtk.vtkFileOutputWindow()
fow.SetFileName("TestEmptyXMLErrors.txt")
fow.SetFlush(0)
fow.SetInstance(fow)

# Prepare some test files.
f = open('emptyFile.vtk', 'wb')
f.close()
f = open('junkFile.vtk', 'wb')
f.write("v9np7598mapwcawoiur-,rjpmW9MJV28nun-q38ynq-9.8ugujqvt-8n3-nv8")
f.close()

# Test each writer/reader.
for t in types:
    type = t[0]
    ext = t[1]
Example #46
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
Example #47
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