示例#1
0
    def chunk_contour(data, prev, *args):
        envelope, values = args

        vti = vtk.vtkImageData()
        vti.SetOrigin(data.origin)
        vti.SetDimensions(np.array(data.shape) - np.array(envelope))
        vti.SetSpacing(data.spacing)
        series_name = "sparse"
        add_np_to_vti(vti, data[:-envelope[0], :-envelope[1], :-envelope[2]],
                      series_name)
        vti.GetPointData().SetActiveScalars(series_name)
        contour = vtk.vtkImageMarchingCubes()
        contour.SetInputData(vti)
        contour.SetNumberOfContours(values.shape[0])
        for i, v in enumerate(values):
            contour.SetValue(i, v)
        contour.ComputeScalarsOn()
        contour.Update()

        writer = vtk.vtkPolyDataWriter()
        writer.SetInputData(contour.GetOutput())
        writer.WriteToOutputStringOn()
        writer.Update()
        prev.append(writer.GetOutputString())

        # TODO: could this return (None, prev) after issue #16 ?
        return data, prev
示例#2
0
    def setupImageProcessingPipeline(self):
        # Gaussian Smooth the image first
        # http://www.vtk.org/doc/nightly/html/classvtkImageGaussianSmooth.html
        self.noiseFilter = vtk.vtkImageGaussianSmooth()
        self.noiseFilter.SetStandardDeviation(1, 1, 1)
        self.noiseFilter.SetRadiusFactors(10, 10, 10)

        # Image Resize for resampler
        # http://www.vtk.org/doc/nightly/html/classvtkImageResize.html
        self.resampler = vtk.vtkImageResize()
        self.resampler.SetResizeMethodToMagnificationFactors()
        self.resampler.SetMagnificationFactors(1, 1, 1)
        self.resampler.BorderOn()
        self.resampler.SetInputConnection(self.noiseFilter.GetOutputPort())

        # Marching cubes for iso value
        # http://www.vtk.org/doc/nightly/html/classvtkImageMarchingCubes.html
        self.marchingCubes = vtk.vtkImageMarchingCubes()
        self.marchingCubes.SetInputConnection(self.resampler.GetOutputPort())
        self.marchingCubes.ComputeGradientsOn()
        self.marchingCubes.ComputeNormalsOn()
        self.marchingCubes.ComputeScalarsOn()
        self.marchingCubes.SetNumberOfContours(1)
        self.marchingCubes.SetValue(0, 0)

        # Create mapper and actor for renderer
        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInputConnection(self.marchingCubes.GetOutputPort())
        self.actor = vtk.vtkActor()
        self.actor.SetMapper(self.mapper)
        self.actor.GetProperty().SetInterpolationToGouraud()
示例#3
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkImageMarchingCubes(), 'Processing.',
         ('vtkImageData',), ('vtkPolyData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
def vtk_marching_cubes(field,iso=0.5):

    import vtk

    int_field = (np.minimum(field*255,255)).astype(np.uint8)
    nx, ny, nz = int_field.shape
    data_string = int_field.tostring('F')

    reader = vtk.vtkImageImport()
    reader.CopyImportVoidPointer(data_string, len(data_string))
    reader.SetDataScalarTypeToUnsignedChar()
    reader.SetNumberOfScalarComponents(1)
    reader.SetDataExtent(0, nx - 1, 0, ny - 1, 0, nz - 1)
    reader.SetWholeExtent(0, nx - 1, 0, ny - 1, 0, nz - 1)
    reader.Update()

    contour = vtk.vtkImageMarchingCubes()
    if vtk.VTK_MAJOR_VERSION <= 5:
        contour.SetInput(reader.GetOutput())
    else:
        contour.SetInputData(reader.GetOutput())   
    contour.ComputeNormalsOn()
    contour.ComputeGradientsOn()
    contour.SetValue(0,int(iso*255))
    contour.Update()

    field_polydata = contour.GetOutput()

    polydata_points = np.array([field_polydata.GetPoints().GetPoint(p) for p in xrange(field_polydata.GetPoints().GetNumberOfPoints())])
    polydata_triangles =  np.array([[field_polydata.GetCell(t).GetPointIds().GetId(i) for i in xrange(3)] for t in xrange(field_polydata.GetNumberOfCells())])

    return polydata_points, polydata_triangles
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkImageMarchingCubes(),
                                       'Processing.', ('vtkImageData', ),
                                       ('vtkPolyData', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
示例#6
0
    def __init__(self):
        super(DualFlouroSceneVisualizer, self).__init__()

        # Remove origin information
        self.xray_changer_1 = vtk.vtkImageChangeInformation()
        self.xray_changer_1.SetOutputOrigin(0, 0, 0)
        self.xray_changer_2 = vtk.vtkImageChangeInformation()
        self.xray_changer_2.SetOutputOrigin(0, 0, 0)
        self.ct_changer = vtk.vtkImageChangeInformation()
        self.ct_changer.SetOutputOrigin(0, 0, 0)

        # Setup mapper and actor for x-ray images
        self.xray_mapper_1 = vtk.vtkImageSliceMapper()
        self.xray_mapper_1.SetInputConnection(
            self.xray_changer_1.GetOutputPort())
        self.xray_mapper_2 = vtk.vtkImageSliceMapper()
        self.xray_mapper_2.SetInputConnection(
            self.xray_changer_2.GetOutputPort())

        self.xray_property = vtk.vtkImageProperty()
        self.xray_property.SetInterpolationTypeToNearest()

        self.xray_slice_1 = vtk.vtkImageSlice()
        self.xray_slice_1.SetMapper(self.xray_mapper_1)
        self.xray_slice_1.SetProperty(self.xray_property)

        self.xray_slice_2 = vtk.vtkImageSlice()
        self.xray_slice_2.SetMapper(self.xray_mapper_2)
        self.xray_slice_2.SetProperty(self.xray_property)

        self.marchingCubes = vtk.vtkImageMarchingCubes()
        self.marchingCubes.SetInputConnection(self.ct_changer.GetOutputPort())
        self.marchingCubes.ComputeGradientsOn()
        self.marchingCubes.ComputeNormalsOn()
        self.marchingCubes.ComputeScalarsOn()
        self.marchingCubes.SetNumberOfContours(1)
        self.marchingCubes.SetValue(0, 0)

        self.ct_mapper = vtk.vtkPolyDataMapper()
        self.ct_mapper.SetInputConnection(self.marchingCubes.GetOutputPort())
        self.ct_mapper.ScalarVisibilityOff()
        self.ct_actor = vtk.vtkActor()
        self.ct_actor.SetMapper(self.ct_mapper)
        self.ct_actor.GetProperty().SetInterpolationToGouraud()
        self.ct_actor.GetProperty().SetColor(GetRGBColor('antique_white'))

        self.renderer = vtk.vtkRenderer()
        self.renderer.AddViewProp(self.ct_actor)
        self.renderer.AddViewProp(self.xray_slice_1)
        self.renderer.AddViewProp(self.xray_slice_2)
        self.renderer.SetBackground(0.1, 0.2, 0.3)

        self.interactor = vtk.vtkRenderWindowInteractor()
        self.interactor_style = vtk.vtkInteractorStyleTrackballCamera()
        self.interactor.SetInteractorStyle(self.interactor_style)
示例#7
0
    def _update_region(self, org_x, org_y, org_z, update_size):
        '''
        :param pa, pb, pc: Requires tuple format of 3 coordinates TCL
        Update region inside the box constructed by pa, pb and pc
        '''
        for i in range(org_x, org_x + update_size):
            for j in range(org_y, org_y + update_size):
                for k in range(org_z, org_z + update_size):
                    self.reader.GetOutput().SetScalarComponentFromFloat(i, j, k, 0, 255)

        # self.voi = vtk.vtkExtractVOI()
        # self.voi.SetInputConnection(self.reader.GetOutputPort())
        # self.voi.SetVOI(org_x, org_x + update_size,
        #                 org_y, org_y + update_size,
        #                 org_z, org_z + update_size)
        # self.voi.Update()

        self.regionMC = vtk.vtkImageMarchingCubes()
        self.regionMC.SetInputConnection(self.reader.GetOutputPort())
        self.regionMC.SetValue(0, self.ui.mc_spin.value())
        self.regionMC.Update()

        # self.mc.SetInputConnection(self.reader.GetOutputPort())
        # self.mc.Update()

        # self.appendData = vtk.vtkAppendPolyData()
        # self.appendData.AddInputData(self.mc.GetOutput())
        # self.appendData.AddInputData(self.regionMC.GetOutput())
        # self.mapper.SetInputConnection(self.appendData.GetOutputPort())

        self.mapper2 = vtk.vtkPolyDataMapper()
        self.mapper2.SetInputConnection(self.regionMC.GetOutputPort())
        self.volumeMapper = vtk.vtkVolumeMapper()
        self.volumeMapper.SetCropping(1)
        self.volumeMapper.SetCroppingRegionPlanes(org_x, org_x + update_size,
                                                  org_y, org_y + update_size,
                                                  org_z, org_z + update_size)
        self.volumeMapper.SetCroppingRegionFlags(0x0002000)

        self.volume = vtk.vtkVolume()
        self.volume.SetMapper(self.volumeMapper)

        self.upperRender = vtk.vtkRenderer()
        self.upperRender.AddVolume(self.volume)
        self.upperRender.SetBackground(0.9, 0.9, 0.9)
        self.upperRender.SetLayer(2)
        self.vtk3DWidget.GetRenderWindow().AddRenderer(self.upperRender)
    def createMesh(self, polyData, spacing):
        dv = 1.75
        rf = 1
        data_matrix = polyData
        data_matrix = np.rot90(data_matrix, 1)
        data_matrix = data_matrix.astype(np.uint8)
        xSize, ySize, zSize = data_matrix.shape

        #================================BoneExtrctor==================================
        dataImporter = vtk.vtkImageImport()
        data_string = data_matrix.tostring()
        dataImporter.CopyImportVoidPointer(data_string, len(data_string))
        dataImporter.SetDataScalarTypeToUnsignedChar()
        dataImporter.SetNumberOfScalarComponents(1)

        dataImporter.SetDataExtent(0, xSize - 1, 0, ySize - 1, 0, zSize - 1)
        dataImporter.SetWholeExtent(0, xSize - 1, 0, ySize - 1, 0, zSize - 1)
        dataImporter.SetDataExtentToWholeExtent()

        #============================= Smoothed pipeline ==============================
        smooth = vtk.vtkImageGaussianSmooth()
        smooth.SetDimensionality(3)
        smooth.SetInputConnection(dataImporter.GetOutputPort())
        smooth.SetStandardDeviations(dv, dv, dv)
        smooth.SetRadiusFactor(rf)

        subsampleSmoothed = vtk.vtkImageShrink3D()
        subsampleSmoothed.SetInputConnection(smooth.GetOutputPort())
        subsampleSmoothed.SetShrinkFactors(4, 4, 1)

        isoSmoothed = vtk.vtkImageMarchingCubes()
        isoSmoothed.SetInputConnection(smooth.GetOutputPort())
        isoSmoothed.SetValue(0, 10)

        isoSmoothedMapper = vtk.vtkPolyDataMapper()
        isoSmoothedMapper.SetInputConnection(isoSmoothed.GetOutputPort())
        isoSmoothedMapper.ScalarVisibilityOff()

        tmpTransfor = vtk.vtkTransform()
        tmpTransfor.Scale(spacing)

        meshActor = vtk.vtkActor()
        meshActor.SetMapper(isoSmoothedMapper)
        meshActor.SetUserTransform(tmpTransfor)

        return meshActor
示例#9
0
  def __init__(self, parent=None):
    
    # Defaults
    self.filename = ""
    self.gaussStandardDeviation = 1.2
    self.gaussRadius = 2
    self.magnification = 1
    self.isosurface = 1
    self.actorColor = [1.000, 0.000, 0.000]
    self.actorOpacity = 1.0
    self.actorVisibility = 1
    self.actorPickable = 1
    
    self.pipelineType = "MarchingCubes" # In the future we could define other types of pipelines
    self.pipelineDataType = None
    self.actorAdded = False
    
    self.processing_log = None
    self.image_info = None
    
    # Elements of the VTK pipeline
    self.reader = None
    self.gauss = vtk.vtkImageGaussianSmooth()
    self.pad = vtk.vtkImageConstantPad()
    self.resampler = vtk.vtkImageResize()
    self.marchingCubes = vtk.vtkImageMarchingCubes()
    self.mapper = vtk.vtkPolyDataMapper()
    self.mapperDS = vtk.vtkDataSetMapper()
    self.actor = vtk.vtkActor()
    self.transformPolyData = vtk.vtkTransformPolyDataFilter()
    
    # The vtkTransform is part of the pipeline. The matrix defines the vtkTransform, but we
    # store a copy in self.matrix for retrieval later.
    self.rigidBodyTransform = vtk.vtkTransform()
    self.rigidBodyTransform.Identity()
    self.rigidBodyTransform.PostMultiply() # Important so that transform concatenations is correct!

    self.matrix = vtk.vtkMatrix4x4()
    self.dim = [1,1,1]
    self.pos = [0,0,0]
    self.el_size_mm = [0.082,0.082,0.082]
    self.extent = [0,1,0,1,0,1]
    self.origin = [0,0,0]
    self.validForExtrusion = False
示例#10
0
    def __init__(self, input_file, gaussian, radius, isosurface, window_size,
                 *args, **kwargs):
        """MainWindow constructor"""
        super().__init__(*args, **kwargs)

        # Window setup
        self.resize(window_size[0], window_size[1])
        self.title = "Basic Qt Viewer for MDSC 689.03"

        self.statusBar().showMessage("Welcome.", 8000)

        # Capture defaults
        self.gaussian = gaussian
        self.radius = radius
        self.isosurface = isosurface

        # Initialize the window
        self.initUI()

        # Set up some VTK pipeline classes
        self.reader = None
        self.gauss = vtk.vtkImageGaussianSmooth()
        self.marchingCubes = vtk.vtkImageMarchingCubes()
        self.mapper = vtk.vtkPolyDataMapper()
        self.actor = vtk.vtkActor()

        # Take inputs from command line. Only use these if there is an input file specified
        if (input_file != None):
            if (not os.path.exists(input_file)):
                qtw.QMessageBox.warning(self, "Error", "Invalid input file.")
                return

            #_,ext = os.path.splitext(input_file)
            #if not (self.validExtension(ext.lower())):
            #  qtw.QMessageBox.warning(self, "Error", "Invalid file type.")
            #  return

            self.createPipeline(input_file)
            self.statusBar().showMessage("Loading file " + input_file, 4000)
            self.changeSigma(gaussian)
            self.changeRadius(radius)
            self.changeIsosurface(isosurface)
示例#11
0
    def _makeSTL(self):
        local_dir = self._gray_dir
        surface_dir = self._vol_dir+'_surfaces'+self._path_dlm
        try:
            os.mkdir(surface_dir)
        except:
            pass
        files = fnmatch.filter(sorted(os.listdir(local_dir)),'*.tif')
        counter = re.search("[0-9]*\.tif", files[0]).group()
        prefix = self._path_dlm+string.replace(files[0],counter,'')
        counter = str(len(counter)-4)
        prefixImageName = local_dir + prefix

        ### Create the renderer, the render window, and the interactor. The renderer
        # The following reader is used to read a series of 2D slices (images)
        # that compose the volume. The slice dimensions are set, and the
        # pixel spacing. The data Endianness must also be specified. The reader
        v16=vtk.vtkTIFFReader()

        v16.SetFilePrefix(prefixImageName)
        v16.SetDataExtent(0,100,0,100,1,len(files))
        v16.SetFilePattern("%s%0"+counter+"d.tif")
        v16.Update()

        im = v16.GetOutput()
        im.SetSpacing(self._pixel_dim[0],self._pixel_dim[1],self._pixel_dim[2])

        v = vte.vtkImageExportToArray()
        v.SetInputData(im)

        n = np.float32(v.GetArray())
        idx = np.argwhere(n)
        (ystart,xstart,zstart), (ystop,xstop,zstop) = idx.min(0),idx.max(0)+1
        I,J,K = n.shape
        if ystart > 5:
            ystart -= 5
        else:
            ystart = 0
        if ystop < I-5:
            ystop += 5
        else:
            ystop = I
        if xstart > 5:
            xstart -= 5
        else:
            xstart = 0
        if xstop < J-5:
            xstop += 5
        else:
            xstop = J
        if zstart > 5:
            zstart -= 5
        else:
            zstart = 0
        if zstop < K-5:
            zstop += 5
        else:
            zstop = K

        a = n[ystart:ystop,xstart:xstop,zstart:zstop]
        itk_img = sitk.GetImageFromArray(a)
        itk_img.SetSpacing([self._pixel_dim[0],self._pixel_dim[1],self._pixel_dim[2]])
        
        print "\n"
        print "-------------------------------------------------------"
        print "-- Applying Patch Based Denoising - this can be slow --"
        print "-------------------------------------------------------"
        print "\n"
        pb = sitk.PatchBasedDenoisingImageFilter()
        pb.KernelBandwidthEstimationOn()
        pb.SetNoiseModel(3) #use a Poisson noise model since this is confocal
        pb.SetNoiseModelFidelityWeight(1)
        pb.SetNumberOfSamplePatches(20)
        pb.SetPatchRadius(4)
        pb.SetNumberOfIterations(10)

        fimg = pb.Execute(itk_img)
        b = sitk.GetArrayFromImage(fimg)
        intensity = b.max()

        #grad = sitk.GradientMagnitudeRecursiveGaussianImageFilter()
        #grad.SetSigma(0.05)
        gf = sitk.GradientMagnitudeImageFilter()
        gf.UseImageSpacingOn()
        grad = gf.Execute(fimg)
        edge = sitk.Cast(sitk.BoundedReciprocal( grad ),sitk.sitkFloat32)


        print "\n"
        print "-------------------------------------------------------"
        print "---- Thresholding to deterimine initial level sets ----"
        print "-------------------------------------------------------"
        print "\n"
        t = 0.5
        seed = sitk.BinaryThreshold(fimg,t*intensity)
        #Opening (Erosion/Dilation) step to remove islands smaller than 2 voxels in radius)
        seed = sitk.BinaryMorphologicalOpening(seed,2)
        seed = sitk.BinaryFillhole(seed!=0)
        #Get connected regions
        r = sitk.ConnectedComponent(seed)
        labels = sitk.GetArrayFromImage(r)
        ids = sorted(np.unique(labels))
        N = len(ids)
        if N > 2:
            i = np.copy(N)
            while i == N and (t-self._tratio)>-1e-7:
                t -= 0.01
                seed = sitk.BinaryThreshold(fimg,t*intensity)
                #Opening (Erosion/Dilation) step to remove islands smaller than 2 voxels in radius)
                seed = sitk.BinaryMorphologicalOpening(seed,2)
                seed = sitk.BinaryFillhole(seed!=0)
                #Get connected regions
                r = sitk.ConnectedComponent(seed)
                labels = sitk.GetArrayFromImage(r)
                i = len(np.unique(labels))
                if i > N:
                    N = np.copy(i)
            t+=0.01
        else:
            t = np.copy(self._tratio)
        seed = sitk.BinaryThreshold(fimg,t*intensity)
        #Opening (Erosion/Dilation) step to remove islands smaller than 2 voxels in radius)
        seed = sitk.BinaryMorphologicalOpening(seed,2)
        seed = sitk.BinaryFillhole(seed!=0)
        #Get connected regions
        r = sitk.ConnectedComponent(seed)
        labels = sitk.GetArrayFromImage(r)
        labels = np.unique(labels)[1:]

        '''
        labels[labels==0] = -1
        labels = sitk.GetImageFromArray(labels)
        labels.SetSpacing([self._pixel_dim[0],self._pixel_dim[1],self._pixel_dim[2]])
        #myshow3d(labels,zslices=range(20))
        #plt.show()
        ls = sitk.ScalarChanAndVeseDenseLevelSetImageFilter()
        ls.UseImageSpacingOn()
        ls.SetLambda2(1.5)
        #ls.SetCurvatureWeight(1.0)
        ls.SetAreaWeight(1.0)
        #ls.SetReinitializationSmoothingWeight(1.0)
        ls.SetNumberOfIterations(100)
        seg = ls.Execute(sitk.Cast(labels,sitk.sitkFloat32),sitk.Cast(fimg,sitk.sitkFloat32))
        seg = sitk.Cast(seg,sitk.sitkUInt8)
        seg = sitk.BinaryMorphologicalOpening(seg,1)
        seg = sitk.BinaryFillhole(seg!=0)
        #Get connected regions
        #r = sitk.ConnectedComponent(seg)
        contours = sitk.BinaryContour(seg)
        myshow3d(sitk.LabelOverlay(sitk.Cast(fimg,sitk.sitkUInt8),contours),zslices=range(fimg.GetSize()[2]))
        plt.show()
        '''

        segmentation = sitk.Image(r.GetSize(),sitk.sitkUInt8)
        segmentation.SetSpacing([self._pixel_dim[0],self._pixel_dim[1],self._pixel_dim[2]])
        for l in labels:
            d = sitk.SignedMaurerDistanceMap(r==l,insideIsPositive=False,squaredDistance=True,useImageSpacing=True)
            #d = sitk.BinaryThreshold(d,-1000,0)
            #d = sitk.Cast(d,edge.GetPixelIDValue() )*-1+0.5
            #d = sitk.Cast(d,edge.GetPixelIDValue() )
            seg = sitk.GeodesicActiveContourLevelSetImageFilter()
            seg.SetPropagationScaling(1.0)
            seg.SetAdvectionScaling(1.0)
            seg.SetCurvatureScaling(0.5)
            seg.SetMaximumRMSError(0.01)
            levelset = seg.Execute(d,edge)
            levelset = sitk.BinaryThreshold(levelset,-1000,0)
            segmentation = sitk.Add(segmentation,levelset)
            print ("RMS Change for Cell %d: "% l,seg.GetRMSChange())
            print ("Elapsed Iterations for Cell %d: "% l, seg.GetElapsedIterations())
        '''
        contours = sitk.BinaryContour(segmentation)
        myshow3d(sitk.LabelOverlay(sitk.Cast(fimg,sitk.sitkUInt8),contours),zslices=range(fimg.GetSize()[2]))
        plt.show()
        '''

        n[ystart:ystop,xstart:xstop,zstart:zstop] = sitk.GetArrayFromImage(segmentation)*100

        i = vti.vtkImageImportFromArray()
        i.SetDataSpacing([self._pixel_dim[0],self._pixel_dim[1],self._pixel_dim[2]])
        i.SetDataExtent([0,100,0,100,1,len(files)])
        i.SetArray(n)
        i.Update()

        thres=vtk.vtkImageThreshold()
        thres.SetInputData(i.GetOutput())
        thres.ThresholdByLower(0)
        thres.ThresholdByUpper(101)

        iso=vtk.vtkImageMarchingCubes()
        iso.SetInputConnection(thres.GetOutputPort())
        iso.SetValue(0,1)

        regions = vtk.vtkConnectivityFilter()
        regions.SetInputConnection(iso.GetOutputPort())
        regions.SetExtractionModeToAllRegions()
        regions.ColorRegionsOn()
        regions.Update()

        N = regions.GetNumberOfExtractedRegions()
        for i in xrange(N):
            r = vtk.vtkConnectivityFilter()
            r.SetInputConnection(iso.GetOutputPort())
            r.SetExtractionModeToSpecifiedRegions()
            r.AddSpecifiedRegion(i)
            g = vtk.vtkExtractUnstructuredGrid()
            g.SetInputConnection(r.GetOutputPort())
            geo = vtk.vtkGeometryFilter()
            geo.SetInputConnection(g.GetOutputPort())
            geo.Update()
            t = vtk.vtkTriangleFilter()
            t.SetInputConnection(geo.GetOutputPort())
            t.Update()
            cleaner = vtk.vtkCleanPolyData()
            cleaner.SetInputConnection(t.GetOutputPort())
            s = vtk.vtkSmoothPolyDataFilter()
            s.SetInputConnection(cleaner.GetOutputPort())
            s.SetNumberOfIterations(50)
            dl = vtk.vtkDelaunay3D()
            dl.SetInputConnection(s.GetOutputPort())
            dl.Update()

            self.cells.append(dl)

        for i in xrange(N):
            g = vtk.vtkGeometryFilter()
            g.SetInputConnection(self.cells[i].GetOutputPort())
            t = vtk.vtkTriangleFilter()
            t.SetInputConnection(g.GetOutputPort())

            #get the surface points of the cells and save to points attribute
            v = t.GetOutput()
            points = []
            for j in xrange(v.GetNumberOfPoints()):
                p = [0,0,0]
                v.GetPoint(j,p)
                points.append(p)
            self.points.append(points)

            #get the volume of the cell
            vo = vtk.vtkMassProperties()
            vo.SetInputConnection(t.GetOutputPort())
            self.volumes.append(vo.GetVolume())

            stl = vtk.vtkSTLWriter()
            stl.SetInputConnection(t.GetOutputPort())
            stl.SetFileName(surface_dir+'cell%02d.stl' % (i+self._counter))
            stl.Write()

        if self._display:
            skinMapper = vtk.vtkDataSetMapper()
            skinMapper.SetInputConnection(regions.GetOutputPort())
            skinMapper.SetScalarRange(regions.GetOutput().GetPointData().GetArray("RegionId").GetRange())
            skinMapper.SetColorModeToMapScalars()
            #skinMapper.ScalarVisibilityOff()
            skinMapper.Update()

            skin = vtk.vtkActor()
            skin.SetMapper(skinMapper)
            #skin.GetProperty().SetColor(0,0,255)

            # An outline provides context around the data.
            #
            outlineData = vtk.vtkOutlineFilter()
            outlineData.SetInputConnection(v16.GetOutputPort())

            mapOutline = vtk.vtkPolyDataMapper()
            mapOutline.SetInputConnection(outlineData.GetOutputPort())

            outline = vtk.vtkActor()
            #outline.SetMapper(mapOutline)
            #outline.GetProperty().SetColor(0,0,0)

            colorbar = vtk.vtkScalarBarActor()
            colorbar.SetLookupTable(skinMapper.GetLookupTable())
            colorbar.SetTitle("Cells")
            colorbar.SetNumberOfLabels(N)


            # Create the renderer, the render window, and the interactor. The renderer
            # draws into the render window, the interactor enables mouse- and 
            # keyboard-based interaction with the data within the render window.
            #
            aRenderer = vtk.vtkRenderer()
            renWin = vtk.vtkRenderWindow()
            renWin.AddRenderer(aRenderer)
            iren = vtk.vtkRenderWindowInteractor()
            iren.SetRenderWindow(renWin)

            # It is convenient to create an initial view of the data. The FocalPoint
            # and Position form a vector direction. Later on (ResetCamera() method)
            # this vector is used to position the camera to look at the data in
            # this direction.
            aCamera = vtk.vtkCamera()
            aCamera.SetViewUp (0, 0, -1)
            aCamera.SetPosition (0, 1, 0)
            aCamera.SetFocalPoint (0, 0, 0)
            aCamera.ComputeViewPlaneNormal()

            # Actors are added to the renderer. An initial camera view is created.
            # The Dolly() method moves the camera towards the FocalPoint,
            # thereby enlarging the image.
            aRenderer.AddActor(outline)
            aRenderer.AddActor(skin)
            aRenderer.AddActor(colorbar)
            aRenderer.SetActiveCamera(aCamera)
            aRenderer.ResetCamera ()
            aCamera.Dolly(1.5)

            # Set a background color for the renderer and set the size of the
            # render window (expressed in pixels).
            aRenderer.SetBackground(0.0,0.0,0.0)
            renWin.SetSize(800, 600)

            # Note that when camera movement occurs (as it does in the Dolly()
            # method), the clipping planes often need adjusting. Clipping planes
            # consist of two planes: near and far along the view direction. The 
            # near plane clips out objects in front of the plane the far plane
            # clips out objects behind the plane. This way only what is drawn
            # between the planes is actually rendered.
            aRenderer.ResetCameraClippingRange()

            im=vtk.vtkWindowToImageFilter()
            im.SetInput(renWin)

            iren.Initialize();
            iren.Start();

        #remove gray directory
        shutil.rmtree(local_dir)
示例#12
0
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# create pipeline
#
v16 = vtk.vtkVolume16Reader()
v16.SetDataDimensions(64,64)
v16.GetOutput().SetOrigin(0.0,0.0,0.0)
v16.SetDataByteOrderToLittleEndian()
v16.SetFilePrefix("" + str(VTK_DATA_ROOT) + "/Data/headsq/quarter")
v16.SetImageRange(1,93)
v16.SetDataSpacing(3.2,3.2,1.5)
v16.Update()
iso = vtk.vtkImageMarchingCubes()
iso.SetInputConnection(v16.GetOutputPort())
iso.SetValue(0,1150)
iso.SetInputMemoryLimit(1000)
topPlane = vtk.vtkPlane()
topPlane.SetNormal(0,0,1)
topPlane.SetOrigin(0,0,0.5)
botPlane = vtk.vtkPlane()
botPlane.SetNormal(0,0,-1)
botPlane.SetOrigin(0,0,137.0)
sagPlane = vtk.vtkPlane()
sagPlane.SetNormal(1,0,0)
sagPlane.SetOrigin(100.8,0,0)
capPlanes = vtk.vtkPlaneCollection()
capPlanes.AddItem(topPlane)
capPlanes.AddItem(botPlane)
示例#13
0
文件: main.py 项目: zibneuro/convert
  print("Error: output directory '" + output_folder_name + "' does not exist")
  exit()

# Very important! The following values are for the virtual fish project
voxel_size = [0.798, 0.798, 2.0]
print("\nIMPORTANT: using the following voxel size: " + str(voxel_size[0]) + ", " + str(voxel_size[1]) + ", " + str(voxel_size[2]))
print("the meshes will be saved in " + output_folder_name)

# The VTK stuff
img_reader = vtk.vtkTIFFReader()
# Gaussian image filter
img_smoother = vtk.vtkImageGaussianSmooth()
img_smoother.SetDimensionality(3)
img_smoother.SetRadiusFactor(3)
# Marching cubes
marching_cubes = vtk.vtkImageMarchingCubes()
marching_cubes.SetValue(0, 128)
# Mesh writer
mesh_writer = vtk.vtkPLYWriter()

# First of all, we collect the names of the tiff files
tiff_file_names = list()

# Get the file names of the tif images in the provided folder
for file_name in os.listdir(input_folder_name):
  full_file_name = os.path.join(input_folder_name, file_name)
  
  # We want files only
  if not os.path.isfile(full_file_name):
    continue
  
示例#14
0
def aim2stl(input_file, output_file, transform_file, gaussian, radius, marching_cubes, decimation, visualize, overwrite, func):

  if os.path.isfile(output_file) and not overwrite:
    result = input('File \"{}\" already exists. Overwrite? [y/n]: '.format(output_file))
    if result.lower() not in ['y', 'yes']:
      print('Not overwriting. Exiting...')
      os.sys.exit()
  
  message("Reading AIM file " + input_file)
  reader = vtkbone.vtkboneAIMReader()
  reader.SetFileName(input_file)
  reader.DataOnCellsOff()
  reader.Update()

  image = reader.GetOutput()
  message("Read %d points from AIM file" % image.GetNumberOfPoints())
  image_bounds = image.GetBounds()
  message("Image bounds:", (" %.4f"*6) % image_bounds)
  image_extent = image.GetExtent()
  message("Image extent:", (" %d"*6) % image_extent)

  message("Gaussian smoothing")
  gauss = vtk.vtkImageGaussianSmooth()
  gauss.SetStandardDeviation(gaussian)
  gauss.SetRadiusFactor(radius)
  gauss.SetInputConnection(reader.GetOutputPort())
  gauss.Update()
  message("Total of %d voxels" % gauss.GetOutput().GetNumberOfCells())
  
  message("Padding the data")
  pad = vtk.vtkImageConstantPad()
  pad.SetConstant(0)
  pad.SetOutputWholeExtent(image_extent[0]-1,image_extent[1]+1,
                           image_extent[2]-1,image_extent[3]+1,
                           image_extent[4]-1,image_extent[5]+1)
  pad.SetInputConnection(gauss.GetOutputPort())
  pad.Update()
  message("Total of %d padded voxels" % pad.GetOutput().GetNumberOfCells())

  message("Extracting isosurface")
  mcube = vtk.vtkImageMarchingCubes()
  mcube.ComputeScalarsOff()
  mcube.ComputeNormalsOff()
  mcube.SetValue(0,marching_cubes)
  mcube.SetInputConnection(pad.GetOutputPort())
  mcube.Update()
  message("Generated %d triangles" % mcube.GetOutput().GetNumberOfCells())
  
  if (decimation>0.0):
    message("Decimating the isosurface. Targeting {:.1f}%".format(decimation*100.0))
    deci = vtk.vtkDecimatePro()
    deci.SetInputConnection(mcube.GetOutputPort())
    deci.SetTargetReduction(decimation) # 0 is none, 1 is maximum decimation.
    deci.Update()
    message("Decimated to %d triangles" % deci.GetOutput().GetNumberOfCells())
    mesh = deci
  else:
    message("No decimation of the isosurface")
    mesh = mcube
  
  mesh = applyTransform(transform_file, mesh)
  
  if (visualize):
    mat4x4 = visualize_actors( mesh.GetOutputPort(), None )
  else:
    mat4x4 = vtk.vtkMatrix4x4()
  
  write_stl( mesh.GetOutputPort(), output_file, mat4x4 )
def setup_vis(file_name):
    print('Reading in {}'.format(file_name))

    # Reader
    vtk.vtkImageReader2Factory.RegisterReader(vtk.vtkNIFTIImageReader())
    reader = vtk.vtkImageReader2Factory.CreateImageReader2(file_name)
    if reader is None:
        os.sys.exit('Cannot find reader for {}'.format(image_file_name))
    reader.SetFileName(file_name)
    reader.Update()
    extent = list(reader.GetOutput().GetExtent())
    print(extent)
    for i in range(0, len(extent), 2):
        extent[i] = extent[i] - 1
        extent[i + 1] = extent[i + 1] + 1
    print(extent)

    # Pad
    padder = vtk.vtkImageConstantPad()
    padder.SetInputConnection(reader.GetOutputPort())
    padder.SetConstant(1)
    padder.SetOutputWholeExtent(extent)

    # Grab surface
    iso = vtk.vtkImageMarchingCubes()
    iso.SetInputConnection(padder.GetOutputPort())
    iso.SetValue(0, 0)
    iso.ComputeNormalsOn()
    iso.ComputeGradientsOn()
    iso.ComputeScalarsOn()

    #iso = vtk.vtkFlyingEdges3D()
    #iso.SetInputConnection(padder.GetOutputPort())
    #iso.SetValue(0,0)
    #iso.ComputeNormalsOn()
    #iso.ComputeGradientsOn()
    #iso.ComputeScalarsOn()
    #iso.InterpolateAttributesOff()

    # Smoother
    #smoother = vtk.vtkWindowedSincPolyDataFilter()
    #smoother.SetInputConnection(iso.GetOutputPort())
    #smoother.SetNumberOfIterations(15)
    #smoother.BoundarySmoothingOff()
    #smoother.FeatureEdgeSmoothingOff()
    #smoother.SetFeatureAngle(120.0)
    #smoother.SetPassBand(0.001)
    #smoother.NonManifoldSmoothingOn()
    #smoother.NormalizeCoordinatesOn()

    # Mapper
    isoMapper = vtk.vtkPolyDataMapper()
    #isoMapper.SetInputConnection(smoother.GetOutputPort())
    isoMapper.SetInputConnection(iso.GetOutputPort())
    isoMapper.ScalarVisibilityOff()
    isoActor = vtk.vtkActor()
    isoActor.SetMapper(isoMapper)
    isoActor.GetProperty().SetColor(1, 1, 1)
    isoActor.GetProperty().SetOpacity(1)

    return isoActor
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)

# create pipeline
#
v16 = vtk.vtkVolume16Reader()
v16.SetDataDimensions(64, 64)
v16.GetOutput().SetOrigin(0.0, 0.0, 0.0)
v16.SetDataByteOrderToLittleEndian()
v16.SetFilePrefix(VTK_DATA_ROOT + "/Data/headsq/quarter")
v16.SetImageRange(1, 93)
v16.SetDataSpacing(3.2, 3.2, 1.5)
v16.Update()

iso = vtk.vtkImageMarchingCubes()
iso.SetInputConnection(v16.GetOutputPort())
iso.SetValue(0, 1150)
iso.SetInputMemoryLimit(1000)

isoMapper = vtk.vtkPolyDataMapper()
isoMapper.SetInputConnection(iso.GetOutputPort())
isoMapper.ScalarVisibilityOff()
isoMapper.ImmediateModeRenderingOn()

isoActor = vtk.vtkActor()
isoActor.SetMapper(isoMapper)
isoActor.GetProperty().SetColor(GetRGBColor('antique_white'))

outline = vtk.vtkOutlineFilter()
outline.SetInputConnection(v16.GetOutputPort())
dataImporter.SetWholeExtent(0, xSize - 1, 0, ySize - 1, 0, zSize - 1)
dataImporter.SetDataExtentToWholeExtent()
#=============================================================================

# Smoothed pipeline.
smooth = vtk.vtkImageGaussianSmooth()
smooth.SetDimensionality(3)
smooth.SetInputConnection(dataImporter.GetOutputPort())
smooth.SetStandardDeviations(dv, dv, dv)
smooth.SetRadiusFactor(rf)

subsampleSmoothed = vtk.vtkImageShrink3D()
subsampleSmoothed.SetInputConnection(smooth.GetOutputPort())
subsampleSmoothed.SetShrinkFactors(4, 4, 1)

isoSmoothed = vtk.vtkImageMarchingCubes()
isoSmoothed.SetInputConnection(smooth.GetOutputPort())
isoSmoothed.SetValue(0, 10)

isoSmoothedMapper = vtk.vtkPolyDataMapper()
isoSmoothedMapper.SetInputConnection(isoSmoothed.GetOutputPort())
isoSmoothedMapper.ScalarVisibilityOff()

colors = vtk.vtkNamedColors()
colors.SetColor("ActorColor", [235, 235, 235, 255])
'''
threshold = vtk.vtkImageThreshold ()
threshold.SetInputConnection(smooth.GetOutputPort())
threshold.ThresholdByLower(10)  # remove all soft tissue
threshold.ReplaceInOn()
threshold.SetInValue(0)  # set all values below 400 to 0
示例#18
0
def main():
    colors = vtk.vtkNamedColors()

    colors.SetColor("ActorColor", [235, 235, 235, 255])

    fileName = get_program_parameters()

    # Read the image.
    readerFactory = vtk.vtkImageReader2Factory()
    reader = readerFactory.CreateImageReader2(fileName)
    reader.SetFileName(fileName)
    reader.Update()

    # Smoothed pipeline.
    smooth = vtk.vtkImageGaussianSmooth()
    smooth.SetDimensionality(3)
    smooth.SetInputConnection(reader.GetOutputPort())
    smooth.SetStandardDeviations(1.75, 1.75, 0.0)
    smooth.SetRadiusFactor(2)

    subsampleSmoothed = vtk.vtkImageShrink3D()
    subsampleSmoothed.SetInputConnection(smooth.GetOutputPort())
    subsampleSmoothed.SetShrinkFactors(4, 4, 1)

    isoSmoothed = vtk.vtkImageMarchingCubes()
    isoSmoothed.SetInputConnection(smooth.GetOutputPort())
    isoSmoothed.SetValue(0, 1150)

    isoSmoothedMapper = vtk.vtkPolyDataMapper()
    isoSmoothedMapper.SetInputConnection(isoSmoothed.GetOutputPort())
    isoSmoothedMapper.ScalarVisibilityOff()

    isoSmoothedActor = vtk.vtkActor()
    isoSmoothedActor.SetMapper(isoSmoothedMapper)
    isoSmoothedActor.GetProperty().SetColor(colors.GetColor3d("ActorColor"))

    # Unsmoothed pipeline.
    # Sub sample the data.
    subsample = vtk.vtkImageShrink3D()
    subsample.SetInputConnection(reader.GetOutputPort())
    subsample.SetShrinkFactors(4, 4, 1)

    iso = vtk.vtkImageMarchingCubes()
    iso.SetInputConnection(subsample.GetOutputPort())
    iso.SetValue(0, 1150)

    isoMapper = vtk.vtkPolyDataMapper()
    isoMapper.SetInputConnection(iso.GetOutputPort())
    isoMapper.ScalarVisibilityOff()

    isoActor = vtk.vtkActor()
    isoActor.SetMapper(isoMapper)
    isoActor.GetProperty().SetColor(colors.GetColor3d("ActorColor"))

    # The rendering Pipeline.

    # Setup the render window, renderer, and interactor.
    leftViewport = [0.0, 0.0, 0.5, 1.0]
    rightViewport = [0.5, 0.0, 1.0, 1.0]

    rendererLeft = vtk.vtkRenderer()
    rendererLeft.SetViewport(leftViewport)

    rendererRight = vtk.vtkRenderer()
    rendererRight.SetViewport(rightViewport)

    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(rendererLeft)
    renderWindow.AddRenderer(rendererRight)

    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    rendererLeft.AddActor(isoActor)
    rendererRight.AddActor(isoSmoothedActor)

    rendererLeft.GetActiveCamera().SetFocalPoint(0.0, 0.0, 0.0)
    rendererLeft.GetActiveCamera().SetPosition(0.0, -1.0, 0.0)
    rendererLeft.GetActiveCamera().SetViewUp(0.0, 0.0, -1.0)
    rendererLeft.ResetCamera()
    rendererLeft.GetActiveCamera().Azimuth(-20.0)
    rendererLeft.GetActiveCamera().Elevation(20.0)
    rendererLeft.ResetCameraClippingRange()

    rendererLeft.SetBackground(colors.GetColor3d("SlateGray"))
    rendererRight.SetBackground(colors.GetColor3d("LightSlateGray"))
    rendererRight.SetActiveCamera(rendererLeft.GetActiveCamera())

    renderWindow.SetSize(640, 480)
    renderWindow.Render()

    renderWindowInteractor.Start()