Exemplo n.º 1
0
    def openFile(self):
        fn = QFileDialog.getOpenFileNames(self, 'Open File')

        # If the user has pressed cancel, the first element of the tuple will be empty.
        # Quit the method cleanly
        if not fn[0]:
            return

        # Single file selection
        if len(fn[0]) == 1:
            file = fn[0][0]

            reader = vtk.vtkMetaImageReader()
            reader.AddObserver("ErrorEvent", self.e)
            reader.SetFileName(file)
            reader.Update()

        # Multiple TIFF files selected
        else:
            # Make sure that the files are sorted 0 - end
            filenames = natsorted(fn[0])

            # Basic test for tiff images
            for file in filenames:
                ftype = imghdr.what(file)
                if ftype != 'tiff':
                    # A non-TIFF file has been loaded, present error message and exit method
                    self.e('','','When reading multiple files, all files must TIFF formatted.')
                    file = file
                    self.displayFileErrorDialog(file)
                    return

            # Have passed basic test, can attempt to load
            numpy_image = Converter.tiffStack2numpyEnforceBounds(filenames=filenames)
            reader = Converter.numpy2vtkImporter(numpy_image)
            reader.Update()

        if self.e.ErrorOccurred():
            self.displayFileErrorDialog(file)

        else:
            self.vtkWidget.viewer.setInput3DData(reader.GetOutput())

        self.setStatusTip('Ready')
 def avgProjections(self, filenames):
     '''Returns the average of the input images
     
     Input is passed as filenames pointing to 2D TIFF
     Output is numpy array
     '''
     num = len(filenames)
     stack = Converter.tiffStack2numpy(filenames=filenames , extent=extent,
                                       sampleRate=(1,1,1))
     avg = (stack.T[0] / float(num) )
     
     for i in range(1,num):
     	avg += (stack.T[i] / float(num))
     
     return avg
 def normalizeProjections(self, projectionFileNames=None, 
                          flatFileNames=None,
                          darkFileNames=None,
                          extent=None, sampleRate=None):
     if projectionFileNames is not None:
         self.setProjectionsFileNames(projectionFileNames)
     if flatFileNames is not None:
         self.setFlatsFileNames(flatFileNames)
     if darkFileNames is not None:
         self.setDarksFileNames(darkFileNames)
         
     flat = self.avgProjections(self.flatsFileNames)
     dark = self.avgProjections(self.darksFileNames)
     
     self.normalizedProjections = Converter.tiffStack2numpy(filenames=self.projectionsFileNames, 
                                      darkField=dark, flatField=flat, 
                                      extent=extent, sampleRate=sampleRate)
tot_images = 2203

## create a reduced 3D stack
nreduced = 360
directory = r'D:\Documents\Dataset\Chadwick_Flange_Tomo'

indices = [int(float(num) / float(nreduced) * float(tot_images)) for num in range(nreduced)]
angle_proj = numpy.asarray(indices) * 180 / tot_images

#load data file
reader = vtk.vtkMetaImageReader()
reader.SetFileName("Chadwick_flange_norm_360.mha")
reader.Update()

norm = Converter.vtk2numpy(reader.GetOutput())

pp = ProjectionPreprocessor()
pp.normalizedProjections = norm
norm = pp.getNormalizedProjections()

cor = 175.75
############################################################
#recon.pars['algorithm'] = Reconstructor.Algorithm.CGLS_CONV
#recon.pars['regularize'] = numpy.double(0.1)
#img_cgls_conv = recon.reconstruct()

niterations = 15
threads = 4

data = (norm.T).copy()
print("append", end1 - start)
while (nop.append_for(np.random.uniform(low=-1, high=1, size=3)) < M):
    pass
end2 = time.time()
print("append_for", end2 - end1)

#%%
gaussians = [{
    'Obj': tp3.Objects3D.PARABOLOID,
    'C0': 1.,
    'x0': float(nop.apoints[loc][0]),
    'y0': float(nop.apoints[loc][1]),
    'z0': float(nop.apoints[loc][2]),
    'a': .2,
    'b': .1,
    'c': .15,
    'phi1': np.random.uniform(low=0, high=360),
    'phi2': np.random.uniform(low=0, high=360),
    'phi3': np.random.uniform(low=0, high=360)
} for loc in range(len(nop.apoints))]

vol = tp3.Object(128, gaussians)
plt.imshow(vol[0])
plt.show()

writer = vtk.vtkMetaImageWriter()
conv = Converter.numpy2vtkImporter(vol)
conv.Update()
writer.SetInputData(conv.GetOutput())
writer.SetFileName("dvc_phantom0.mha")
writer.Write()
Exemplo n.º 6
0
    def openFile(self, progress_callback=None, **kwargs):
        """
        Open file(s) based on results from QFileDialog

        :param (function) progress_callback:
            Callback funtion to emit progress percentage.
        """

        if 'filename' not in kwargs.keys():
            fn = self.fn
        else:
            fn = ([kwargs['filename']],)

        # If the user has pressed cancel, the first element of the tuple will be empty.
        # Quit the method cleanly
        if not fn[0]:
            return

        # Single file selection
        if len(fn[0]) == 1:
            file = fn[0][0]
            if progress_callback:
                progress_callback.emit(30)
            reader = vtk.vtkMetaImageReader()
            reader.AddObserver("ErrorEvent", self.e)
            reader.SetFileName(file)
            reader.Update()
            if progress_callback:
                progress_callback.emit(90)
                self.mainwindow.setStatusTip('File Read: {}'.format(reader.GetOutput().GetExtent()))

        # Multiple TIFF files selected
        else:
            # Make sure that the files are sorted 0 - end
            filenames = natsorted(fn[0])
            increment = 30.0 / len(filenames)


            # Basic test for tiff images
            for n,file in enumerate(filenames,1):
                ftype = imghdr.what(file)
                if ftype != 'tiff':
                    # A non-TIFF file has been loaded, present error message and exit method
                    self.e('','','Problem reading file: {}'.format(file))
                    raise ReadError("File read error!")
                if progress_callback:
                    progress_callback.emit(int(n * increment))

            # Have passed basic test, can attempt to load
            numpy_image = Converter.pureTiff2Numpy(filenames=filenames, bounds=(256,256,256), progress_callback=progress_callback)
            reader = Converter.numpy2vtkImporter(numpy_image)
            reader.Update()

        if self.e.ErrorOccurred():
            raise ReadError()

        else:
            self.viewerWidget.viewer.setInput3DData(reader.GetOutput())
            if progress_callback:
                progress_callback.emit(91)
            self.mainwindow.setStatusTip('display 2D')
            if progress_callback:
                progress_callback.emit(92)
            self.viewer3DWidget.viewer.setInput3DData(reader.GetOutput())
            if progress_callback:
                progress_callback.emit(93)
            self.graph_numpy_input_data = Converter.vtk2numpy(reader.GetOutput(), transpose=[2,1,0])
            if progress_callback:
                progress_callback.emit(94)
            self.mainwindow.setStatusTip('convert to numpy')
            self.mainwindow.setStatusTip('Ready')
            if progress_callback:
                progress_callback.emit(95)
            self.spacing = reader.GetOutput().GetSpacing()
            if progress_callback:
                progress_callback.emit(96)
            self.origin = reader.GetOutput().GetOrigin()
            if progress_callback:
                progress_callback.emit(97)

            ### After successfully opening file, reset the interface ###
            # Reset linked state
            self.linkViewers(force_linked=True)

            # Reset graph if drawn
            self.graphWidget.viewer.update(vtk.vtkMutableDirectedGraph())

            # Reset graph parameter panel
            if self.hasDockableWindow:
                for element in self.treeWidgetInitialElements:
                    element.setEnabled(True)

                for element in self.treeWidgetUpdateElements:
                    element.setEnabled(False)
                    
        print ("finished openFile")
Exemplo n.º 7
0
        surface += 1

    # polydata object
    trianglePolyData = vtk.vtkPolyData()
    trianglePolyData.SetPoints(triangle_vertices)
    trianglePolyData.SetPolys(triangles)
    return trianglePolyData


reader = vtk.vtkMetaImageReader()
reader.SetFileName("../../data/fuel_uc_python.mha")
reader.Update()

seg = SimpleflexSegmentor()
seg.setInputData(Converter.vtk2numpy(reader.GetOutput()))

seg.calculateContourTree()

#seg.setIsoValuePercent(24.)
seg.setLocalIsoValuePercent(0.)
seg.resetCollapsePriority(seg.PRIORITY_VOLUME)

# 5. Construct the iso-surfaces
print("calling resetCollapsePriority")

#seg.updateTreeFromLogTreeSize(size=0.6, isGlobal=False)
print("calling setlogtreesize")
seg.ct.SetLogTreeSize(1)
print("calling UpdateTreeFromLogTreeSize")
seg.ct.UpdateTreeFromLogTreeSize()