def read_data_and_build_snapshot_matrix(x_min,x_max,y_min,y_max,z_min,z_max,snapshot_dir,file_list,\
						num_snapshots,num_points,num_components,var_name, A):
	reader = vtk.vtkUnstructuredGridReader()
	reader.ReadAllScalarsOn()
	reader.ReadAllVectorsOn()
	extract_region = "false"
	if ( (x_min<x_max) and (y_min<y_max) and (z_min<z_max) ):
		extract_region = "true"
		extract = vtk.vtkExtractUnstructuredGrid()
		extract.SetExtent(x_min, x_max, y_min, y_max, z_min, z_max)
		extract.MergingOn()
	u_temp_read = np.array(np.zeros((num_points,3), dtype=np.float64))
	print '\n   Reading data ...'
	for j in range(0,num_snapshots+1):
		print '      Reading file ', file_list[j].strip(), 'file number ', j, ' of ', num_snapshots
		reader.SetFileName(snapshot_dir + file_list[j].strip())
		reader.Update()
		if (extract_region=="true"):
			extract.SetInput(reader.GetOutput())
			extract.Update()
			u_temp_read = VN.vtk_to_numpy(extract.GetOutput().GetPointData().GetVectors(var_name))
		else:
			u_temp_read = VN.vtk_to_numpy(reader.GetOutput().GetPointData().GetVectors(var_name))
		for k in range(0,num_components):
			A[k*num_points:(k+1)*num_points,j] = u_temp_read[:,k]
Пример #2
0
def read_data_and_build_snapshot_matrix(x_min,x_max,y_min,y_max,z_min,z_max,snapshot_dir,file_list,\
      num_snapshots,num_points,num_components,var_name, A):
    reader = vtk.vtkUnstructuredGridReader()
    reader.ReadAllScalarsOn()
    reader.ReadAllVectorsOn()
    extract_region = "false"
    if ((x_min < x_max) and (y_min < y_max) and (z_min < z_max)):
        extract_region = "true"
        extract = vtk.vtkExtractUnstructuredGrid()
        extract.SetExtent(x_min, x_max, y_min, y_max, z_min, z_max)
        extract.MergingOn()
    u_temp_read = np.array(np.zeros((num_points, 3), dtype=np.float64))
    print '\n   Reading data ...'
    for j in range(0, num_snapshots + 1):
        print '      Reading file ', file_list[j].strip(
        ), 'file number ', j, ' of ', num_snapshots
        reader.SetFileName(snapshot_dir + file_list[j].strip())
        reader.Update()
        if (extract_region == "true"):
            extract.SetInput(reader.GetOutput())
            extract.Update()
            u_temp_read = VN.vtk_to_numpy(
                extract.GetOutput().GetPointData().GetVectors(var_name))
        else:
            u_temp_read = VN.vtk_to_numpy(
                reader.GetOutput().GetPointData().GetVectors(var_name))
        for k in range(0, num_components):
            A[k * num_points:(k + 1) * num_points, j] = u_temp_read[:, k]
Пример #3
0
    def update(self):
        """

        """

        appendFilter = vtkAppendFilter()
        appendFilter.AddInput(self.input_)
        appendFilter.Update()

        extractGrid = vtkExtractUnstructuredGrid()
        extractGrid.SetInput(appendFilter.GetOutput())
        extractGrid.SetExtent(self.extent[0], self.extent[1], self.extent[2],
                              self.extent[3], self.extent[4], self.extent[5])

        geom = vtkGeometryFilter()
        geom.SetInputConnection(extractGrid.GetOutputPort())
        geom.Update()

        clean = vtkCleanPolyData()
        clean.PointMergingOn()
        clean.SetTolerance(0.01)
        clean.SetInput(geom.GetOutput())
        clean.Update()

        self.output_ = clean.GetOutput()
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkExtractUnstructuredGrid(), 'Processing.',
         ('vtkUnstructuredGrid',), ('vtkUnstructuredGrid',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Пример #5
0
  def Crop(self, min_x, max_x, min_y, max_y, min_z, max_z):
    """Trim off the edges defined by a bounding box."""
    trimmer = vtk.vtkExtractUnstructuredGrid()
    trimmer.SetInput(self.ugrid)
    trimmer.SetExtent(min_x, max_x, min_y, max_y, min_z, max_z)
    trimmer.Update()
    trimmed_ug = trimmer.GetOutput()

    self.ugrid = trimmed_ug
Пример #6
0
  def Crop(self, min_x, max_x, min_y, max_y, min_z, max_z):
    """Trim off the edges defined by a bounding box."""
    trimmer = vtk.vtkExtractUnstructuredGrid()
    trimmer.SetInputData(self.ugrid)
    trimmer.SetExtent(min_x, max_x, min_y, max_y, min_z, max_z)
    trimmer.Update()
    trimmed_ug = trimmer.GetOutput()

    self.ugrid = trimmed_ug
Пример #7
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkExtractUnstructuredGrid(),
                                       'Processing.',
                                       ('vtkUnstructuredGrid', ),
                                       ('vtkUnstructuredGrid', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
Пример #8
0
  def Crop(self, min_x, max_x, min_y, max_y, min_z, max_z):
    """Trim off the edges defined by a bounding box."""
    trimmer = vtk.vtkExtractUnstructuredGrid()
    if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
      trimmer.SetInput(self.ugrid)
    else:
      trimmer.SetInputData(self.ugrid)
    trimmer.SetExtent(min_x, max_x, min_y, max_y, min_z, max_z)
    trimmer.Update()
    trimmed_ug = trimmer.GetOutput()

    self.ugrid = trimmed_ug
Пример #9
0
	def makeUnstructVTKVOIThres(vtkObj,extent,limits):
		"""Make volume of interest and threshold for rectilinear grid."""
		# Check for the input
		cellCore = vtk.vtkExtractUnstructuredGrid()
		cellCore.SetExtent(extent)
		cellCore.SetInput(vtkObj)

		cellThres = vtk.vtkThreshold()
		cellThres.AllScalarsOn()
		cellThres.SetInputConnection(cellCore.GetOutputPort())
		cellThres.ThresholdBetween(limits[0],limits[1])
		cellThres.Update()
		return cellThres.GetOutput(), cellCore.GetOutput()
Пример #10
0
def get_grid_template(x_min,x_max,y_min,y_max,z_min,z_max,filename,grid):
	reader = vtk.vtkUnstructuredGridReader()
	reader.ReadAllScalarsOn()
	reader.ReadAllVectorsOn()
	reader.SetFileName(filename)
	reader.Update()
	if ( (x_min<x_max) and (y_min<y_max) and (z_min<z_max) ):
		extract = vtk.vtkExtractUnstructuredGrid()
		extract.SetExtent(x_min, x_max, y_min, y_max, z_min, z_max)
		extract.SetInput(reader.GetOutput())
		extract.MergingOn()
		extract.Update()
		grid.DeepCopy(extract.GetOutput())
	else:
		grid.DeepCopy(reader.GetOutput())
Пример #11
0
def get_cell_volumes(x_min,x_max,y_min,y_max,z_min,z_max,filename,cell_volume):
	reader = vtk.vtkUnstructuredGridReader()
	reader.ReadAllScalarsOn()
	reader.ReadAllVectorsOn()
	reader.SetFileName(filename)
	reader.Update()
	if ( (x_min<x_max) and (y_min<y_max) and (z_min<z_max) ):
		extract = vtk.vtkExtractUnstructuredGrid()
		extract.SetExtent(x_min, x_max, y_min, y_max, z_min, z_max)
		extract.SetInput(reader.GetOutput())
		extract.MergingOn()
		extract.Update()
		cell_volume = VN.vtk_to_numpy(extract.GetOutput().GetPointData().GetScalars("cell_volume"))
	else:
		cell_volume = VN.vtk_to_numpy(reader.GetOutput().GetPointData().GetScalars("cell_volume"))
Пример #12
0
def get_grid_template(x_min, x_max, y_min, y_max, z_min, z_max, filename,
                      grid):
    reader = vtk.vtkUnstructuredGridReader()
    reader.ReadAllScalarsOn()
    reader.ReadAllVectorsOn()
    reader.SetFileName(filename)
    reader.Update()
    if ((x_min < x_max) and (y_min < y_max) and (z_min < z_max)):
        extract = vtk.vtkExtractUnstructuredGrid()
        extract.SetExtent(x_min, x_max, y_min, y_max, z_min, z_max)
        extract.SetInput(reader.GetOutput())
        extract.MergingOn()
        extract.Update()
        grid.DeepCopy(extract.GetOutput())
    else:
        grid.DeepCopy(reader.GetOutput())
Пример #13
0
def get_number_of_points(x_min, x_max, y_min, y_max, z_min, z_max, filename):
    reader = vtk.vtkUnstructuredGridReader()
    reader.ReadAllScalarsOn()
    reader.ReadAllVectorsOn()
    reader.SetFileName(filename)
    reader.Update()
    if ((x_min < x_max) and (y_min < y_max) and (z_min < z_max)):
        extract = vtk.vtkExtractUnstructuredGrid()
        extract.SetExtent(x_min, x_max, y_min, y_max, z_min, z_max)
        extract.SetInput(reader.GetOutput())
        extract.MergingOn()
        extract.Update()
        num_points = extract.GetOutput().GetNumberOfPoints()
    else:
        num_points = reader.GetOutput().GetNumberOfPoints()
    print '   Number of points = ', num_points

    return num_points
Пример #14
0
def get_number_of_points(x_min,x_max,y_min,y_max,z_min,z_max,filename):
	reader = vtk.vtkUnstructuredGridReader()
	reader.ReadAllScalarsOn()
	reader.ReadAllVectorsOn()
	reader.SetFileName(filename)
	reader.Update()
	if ( (x_min<x_max) and (y_min<y_max) and (z_min<z_max) ):
		extract = vtk.vtkExtractUnstructuredGrid()
		extract.SetExtent(x_min, x_max, y_min, y_max, z_min, z_max)
		extract.SetInput(reader.GetOutput())
		extract.MergingOn()
		extract.Update()
		num_points = extract.GetOutput().GetNumberOfPoints()
	else:
		num_points = reader.GetOutput().GetNumberOfPoints()
	print '   Number of points = ', num_points

	return num_points
Пример #15
0
def get_cell_volumes(x_min, x_max, y_min, y_max, z_min, z_max, filename,
                     cell_volume):
    reader = vtk.vtkUnstructuredGridReader()
    reader.ReadAllScalarsOn()
    reader.ReadAllVectorsOn()
    reader.SetFileName(filename)
    reader.Update()
    if ((x_min < x_max) and (y_min < y_max) and (z_min < z_max)):
        extract = vtk.vtkExtractUnstructuredGrid()
        extract.SetExtent(x_min, x_max, y_min, y_max, z_min, z_max)
        extract.SetInput(reader.GetOutput())
        extract.MergingOn()
        extract.Update()
        cell_volume = VN.vtk_to_numpy(
            extract.GetOutput().GetPointData().GetScalars("cell_volume"))
    else:
        cell_volume = VN.vtk_to_numpy(
            reader.GetOutput().GetPointData().GetScalars("cell_volume"))
Пример #16
0
    def update(self):
        """

        """

        appendFilter = vtkAppendFilter()
        appendFilter.AddInput(self.input_)
        appendFilter.Update()

        extractGrid = vtkExtractUnstructuredGrid()
        extractGrid.SetInput(appendFilter.GetOutput())
        extractGrid.SetExtent(self.extent[0], self.extent[1], self.extent[2],  self.extent[3],  self.extent[4], self.extent[5])

        geom = vtkGeometryFilter()
        geom.SetInputConnection(extractGrid.GetOutputPort() )
        geom.Update()

        clean = vtkCleanPolyData()
        clean.PointMergingOn()
        clean.SetTolerance(0.01)
        clean.SetInput(geom.GetOutput())
        clean.Update()

        self.output_ = clean.GetOutput()
Пример #17
0
    def Execute(self):

        if self.Mesh == None:
            self.PrintError('Error: no Mesh.')

##        if (self.FOVNormal != [0.0, 0.0, 1.0]):
##                    
##            translation = [-self.FOVCenter[0], -self.FOVCenter[1], -self.FOVCenter[2]]
##    
##            referenceNormal = [0.0, 0.0, 1.0]
##            rotationAxis = [0.0, 0.0, 0.0]
##            vtk.vtkMath.Normalize(self.FOVNormal)
##            vtk.vtkMath.Cross(self.FOVNormal,referenceNormal,rotationAxis)
##            angle = self.AngleBetweenNormals(referenceNormal,self.FOVNormal) / vtk.vtkMath.Pi() * 180.0
##        
##            transform = vtk.vtkTransform()
##            transform.PostMultiply()
##            transform.Translate(translation)
##            transform.RotateWXYZ(angle,rotationAxis)
##            transform.Translate(self.FOVCenter)
##    
##            transformFilter = vtk.vtkTransformFilter()
##            transformFilter.SetInput(self.Mesh)
##            transformFilter.SetTransform(transform)
##            transformFilter.Update()
##            
##            acquiredMesh = transformFilter.GetOutput()

        if (self.KSpaceDimensionality == 3) or not self.SliceModel:

            origin = [self.FOVCenter[0] - self.FOV[0]/2.0,
                      self.FOVCenter[1] - self.FOV[1]/2.0,
                      self.FOVCenter[2] - self.FOV[2]/2.0]

            spacing = [self.FOV[0] / self.MatrixSize[0],
                       self.FOV[1] / self.MatrixSize[1],
                       self.FOV[2] / self.MatrixSize[2]]

            self.KSpace = self.AcquireKSpace(self.Mesh,origin,spacing)

        elif self.KSpaceDimensionality == 2:
            
            kSpaceAppend = vtk.vtkImageAppend()
            kSpaceAppend.SetAppendAxis(2)

            sliceLocations = []
            sliceLocation = self.FOVCenter[2] - self.FOV[2]/2.0
            while (sliceLocation < self.FOVCenter[2] + self.FOV[2]/2.0):
                sliceLocations.append(sliceLocation)
                sliceLocation += self.SliceSpacing

            spacing = [self.FOV[0] / self.MatrixSize[0],
                       self.FOV[1] / self.MatrixSize[1],
                       self.FOV[2] / self.MatrixSize[2]]
            
            bounds = self.Mesh.GetBounds()
           
            for sliceLocation in sliceLocations:

                self.PrintLog("Processing slice at" + float(sliceLocation))

                origin = [self.FOVCenter[0] - self.FOV[0]/2.0,
                          self.FOVCenter[1] - self.FOV[1]/2.0,
                          sliceLocation]
                
                clipper1 = vtk.vtkClipDataSet()
                clipper1.SetInput(self.Mesh)
                clipper1.InsideOutOff()
                
                plane1 = vtk.vtkPlane()
                plane1.SetNormal(0.0,0.0,1.0)
                plane1.SetOrigin(0.0,0.0,sliceLocation - self.SliceThickness / 2.0)

                clipper1.SetClipFunction(plane1)
                clipper1.Update()

                clipper2 = vtk.vtkClipDataSet()
                clipper2.SetInput(clipper1.GetOutput())
                clipper2.InsideOutOn()
                
                plane2 = vtk.vtkPlane()
                plane2.SetNormal(0.0,0.0,1.0)
                plane2.SetOrigin(0.0,0.0,sliceLocation + self.SliceThickness / 2.0)

                clipper2.SetClipFunction(plane2)
                clipper2.Update()

                clipper2Bounds = clipper2.GetOutput().GetBounds()

                cleaner = vtk.vtkExtractUnstructuredGrid()
                cleaner.SetInput(clipper2.GetOutput())
                cleaner.ExtentClippingOn()
                cleaner.SetExtent(clipper2Bounds[0],clipper2Bounds[1],
                                  clipper2Bounds[2],clipper2Bounds[3],
                                  sliceLocation-self.SliceThickness/2.0,sliceLocation+self.SliceThickness/2.0)
                cleaner.Update()

                tetraFilter = vtk.vtkDataSetTriangleFilter()
                tetraFilter.SetInput(cleaner.GetOutput())
                tetraFilter.Update()

                sliceMesh = tetraFilter.GetOutput()

                self.PrintLog("Number of integration elements:" + int(sliceMesh.GetNumberOfCells()))

                sliceKSpace = self.AcquireKSpace(sliceMesh,origin,spacing)

                kSpaceAppend.AddInput(sliceKSpace)
                
            kSpaceAppend.Update()
            
            self.KSpace = self.ComputeKSpaceOperation(kSpaceAppend.GetOutput())
Пример #18
0
 def initialize (self):
     debug ("In ExtractUnstructuredGrid::__init__ ()")
     self.fil = vtk.vtkExtractUnstructuredGrid ()
     self.fil.SetInput (self.prev_fil.GetOutput ())
     self.fil.Update ()        
Пример #19
0
def extract_mesh_subregion(mesh,regionBoundaries):
    subregionAlgorithm = vtkExtractUnstructuredGrid()
    subregionAlgorithm.SetInputData(mesh)
    subregionAlgorithm.SetExtent(regionBoundaries)
    subregionAlgorithm.Update()
    return subregionAlgorithm.GetOutput()
Пример #20
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)
Пример #21
0
moldMapper.ScalarVisibilityOff()
moldActor = vtk.vtkActor()
moldActor.SetMapper(moldMapper)
moldActor.GetProperty().SetColor(.2, .2, .2)
moldActor.GetProperty().SetRepresentationToWireframe()

# Another connectivity filter is used to extract the parison.
connect2 = vtk.vtkConnectivityFilter()
connect2.SetInputConnection(warp.GetOutputPort())
connect2.SetExtractionModeToSpecifiedRegions()
connect2.AddSpecifiedRegion(2)

# We use vtkExtractUnstructuredGrid because we are interested in
# looking at just a few cells. We use cell clipping via cell id to
# extract the portion of the grid we are interested in.
extractGrid = vtk.vtkExtractUnstructuredGrid()
extractGrid.SetInputConnection(connect2.GetOutputPort())
extractGrid.CellClippingOn()
extractGrid.SetCellMinimum(0)
extractGrid.SetCellMaximum(23)
parison = vtk.vtkGeometryFilter()
parison.SetInputConnection(extractGrid.GetOutputPort())
normals2 = vtk.vtkPolyDataNormals()
normals2.SetInputConnection(parison.GetOutputPort())
normals2.SetFeatureAngle(60)
lut = vtk.vtkLookupTable()
lut.SetHueRange(0.0, 0.66667)
parisonMapper = vtk.vtkPolyDataMapper()
parisonMapper.SetInputConnection(normals2.GetOutputPort())
parisonMapper.SetLookupTable(lut)
parisonMapper.SetScalarRange(0.12, 1.0)
connect.SetExtractionModeToSpecifiedRegions()
connect.AddSpecifiedRegion(0)
connect.AddSpecifiedRegion(1)
moldMapper = vtk.vtkDataSetMapper()
moldMapper.SetInputConnection(reader.GetOutputPort())
moldMapper.ScalarVisibilityOff()
moldActor = vtk.vtkActor()
moldActor.SetMapper(moldMapper)
moldActor.GetProperty().SetColor(.2,.2,.2)
moldActor.GetProperty().SetRepresentationToWireframe()
# extract parison from mesh using connectivity
connect2 = vtk.vtkConnectivityFilter()
connect2.SetInputConnection(warp.GetOutputPort())
connect2.SetExtractionModeToSpecifiedRegions()
connect2.AddSpecifiedRegion(2)
extractGrid = vtk.vtkExtractUnstructuredGrid()
extractGrid.SetInputConnection(connect2.GetOutputPort())
extractGrid.CellClippingOn()
extractGrid.SetCellMinimum(0)
extractGrid.SetCellMaximum(23)
parison = vtk.vtkGeometryFilter()
parison.SetInputConnection(extractGrid.GetOutputPort())
normals2 = vtk.vtkPolyDataNormals()
normals2.SetInputConnection(parison.GetOutputPort())
normals2.SetFeatureAngle(60)
lut = vtk.vtkLookupTable()
lut.SetHueRange(0.0,0.66667)
parisonMapper = vtk.vtkPolyDataMapper()
parisonMapper.SetInputConnection(normals2.GetOutputPort())
parisonMapper.SetLookupTable(lut)
parisonMapper.SetScalarRange(0.12,1.0)
Пример #23
0
    def Execute(self):

        if self.Mesh == None:
            self.PrintError('Error: no Mesh.')


##        if (self.FOVNormal != [0.0, 0.0, 1.0]):
##
##            translation = [-self.FOVCenter[0], -self.FOVCenter[1], -self.FOVCenter[2]]
##
##            referenceNormal = [0.0, 0.0, 1.0]
##            rotationAxis = [0.0, 0.0, 0.0]
##            vtk.vtkMath.Normalize(self.FOVNormal)
##            vtk.vtkMath.Cross(self.FOVNormal,referenceNormal,rotationAxis)
##            angle = self.AngleBetweenNormals(referenceNormal,self.FOVNormal) / vtk.vtkMath.Pi() * 180.0
##
##            transform = vtk.vtkTransform()
##            transform.PostMultiply()
##            transform.Translate(translation)
##            transform.RotateWXYZ(angle,rotationAxis)
##            transform.Translate(self.FOVCenter)
##
##            transformFilter = vtk.vtkTransformFilter()
##            transformFilter.SetInput(self.Mesh)
##            transformFilter.SetTransform(transform)
##            transformFilter.Update()
##
##            acquiredMesh = transformFilter.GetOutput()

        if (self.KSpaceDimensionality == 3) or not self.SliceModel:

            origin = [
                self.FOVCenter[0] - self.FOV[0] / 2.0,
                self.FOVCenter[1] - self.FOV[1] / 2.0,
                self.FOVCenter[2] - self.FOV[2] / 2.0
            ]

            spacing = [
                self.FOV[0] / self.MatrixSize[0],
                self.FOV[1] / self.MatrixSize[1],
                self.FOV[2] / self.MatrixSize[2]
            ]

            self.KSpace = self.AcquireKSpace(self.Mesh, origin, spacing)

        elif self.KSpaceDimensionality == 2:

            kSpaceAppend = vtk.vtkImageAppend()
            kSpaceAppend.SetAppendAxis(2)

            sliceLocations = []
            sliceLocation = self.FOVCenter[2] - self.FOV[2] / 2.0
            while (sliceLocation < self.FOVCenter[2] + self.FOV[2] / 2.0):
                sliceLocations.append(sliceLocation)
                sliceLocation += self.SliceSpacing

            spacing = [
                self.FOV[0] / self.MatrixSize[0],
                self.FOV[1] / self.MatrixSize[1],
                self.FOV[2] / self.MatrixSize[2]
            ]

            bounds = self.Mesh.GetBounds()

            for sliceLocation in sliceLocations:

                self.PrintLog("Processing slice at" + float(sliceLocation))

                origin = [
                    self.FOVCenter[0] - self.FOV[0] / 2.0,
                    self.FOVCenter[1] - self.FOV[1] / 2.0, sliceLocation
                ]

                clipper1 = vtk.vtkClipDataSet()
                clipper1.SetInput(self.Mesh)
                clipper1.InsideOutOff()

                plane1 = vtk.vtkPlane()
                plane1.SetNormal(0.0, 0.0, 1.0)
                plane1.SetOrigin(0.0, 0.0,
                                 sliceLocation - self.SliceThickness / 2.0)

                clipper1.SetClipFunction(plane1)
                clipper1.Update()

                clipper2 = vtk.vtkClipDataSet()
                clipper2.SetInput(clipper1.GetOutput())
                clipper2.InsideOutOn()

                plane2 = vtk.vtkPlane()
                plane2.SetNormal(0.0, 0.0, 1.0)
                plane2.SetOrigin(0.0, 0.0,
                                 sliceLocation + self.SliceThickness / 2.0)

                clipper2.SetClipFunction(plane2)
                clipper2.Update()

                clipper2Bounds = clipper2.GetOutput().GetBounds()

                cleaner = vtk.vtkExtractUnstructuredGrid()
                cleaner.SetInput(clipper2.GetOutput())
                cleaner.ExtentClippingOn()
                cleaner.SetExtent(clipper2Bounds[0], clipper2Bounds[1],
                                  clipper2Bounds[2], clipper2Bounds[3],
                                  sliceLocation - self.SliceThickness / 2.0,
                                  sliceLocation + self.SliceThickness / 2.0)
                cleaner.Update()

                tetraFilter = vtk.vtkDataSetTriangleFilter()
                tetraFilter.SetInput(cleaner.GetOutput())
                tetraFilter.Update()

                sliceMesh = tetraFilter.GetOutput()

                self.PrintLog("Number of integration elements:" +
                              int(sliceMesh.GetNumberOfCells()))

                sliceKSpace = self.AcquireKSpace(sliceMesh, origin, spacing)

                kSpaceAppend.AddInput(sliceKSpace)

            kSpaceAppend.Update()

            self.KSpace = self.ComputeKSpaceOperation(kSpaceAppend.GetOutput())