def RollMap(self, baseImage): # baseImage.Update() if self.world_cut == self.map_cut: return baseImage baseExtent = baseImage.GetExtent() baseSpacing = baseImage.GetSpacing() x0 = baseExtent[0] x1 = baseExtent[1] newCut = self.NormalizeMapLon(self.world_cut) delCut = newCut - self.map_cut # print " %%%%%% Roll Map %%%%%%: world_cut=%.1f, map_cut=%.1f, newCut=%.1f " % ( float(self.world_cut), float(self.map_cut), float(newCut) ) imageLen = x1 - x0 + 1 sliceSize = imageLen * (delCut / 360.0) sliceCoord = int(round(x0 + sliceSize)) extent = list(baseExtent) extent[0:2] = [x0, x0 + sliceCoord - 1] clip0 = vtk.vtkImageClip() if vtk.VTK_MAJOR_VERSION <= 5: clip0.SetInput(baseImage) else: clip0.SetInputData(baseImage) clip0.SetOutputWholeExtent(extent[0], extent[1], extent[2], extent[3], extent[4], extent[5]) extent[0:2] = [x0 + sliceCoord, x1] clip1 = vtk.vtkImageClip() if vtk.VTK_MAJOR_VERSION <= 5: clip1.SetInput(baseImage) else: clip1.SetInputData(baseImage) clip1.SetOutputWholeExtent(extent[0], extent[1], extent[2], extent[3], extent[4], extent[5]) clip0.Update() clip1.Update() append = vtk.vtkImageAppend() append.SetAppendAxis(0) if vtk.VTK_MAJOR_VERSION <= 5: append.AddInput(clip1.GetOutput()) append.AddInput(clip0.GetOutput()) else: append.SetInputData(0, clip1.GetOutput()) append.SetInputData(1, clip0.GetOutput()) append.Update() imageInfo = vtk.vtkImageChangeInformation() imageInfo.SetInputConnection(append.GetOutputPort()) imageInfo.SetOutputOrigin(0.0, 0.0, 0.0) imageInfo.SetOutputExtentStart(0, 0, 0) imageInfo.SetOutputSpacing(baseSpacing[0], baseSpacing[1], baseSpacing[2]) imageInfo.Update() result = imageInfo.GetOutput() return result
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkImageClip(), 'Processing.', ('vtkImageData',), ('vtkImageData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def captureImageFromView(self, view, filename): view.forceRender() # qt.QPixmap().grabWidget(...) would not grab the background rw = view.renderWindow() wti = vtk.vtkWindowToImageFilter() wti.SetInput(rw) wti.Update() writer = vtk.vtkPNGWriter() writer.SetFileName(filename) outputImage = wti.GetOutput() imageSize = outputImage.GetDimensions() if imageSize[0] < 2 or imageSize[1] < 2: # image is too small, most likely it is invalid raise ValueError('Capture image from view failed') # Make sure image witdth and height is even, otherwise encoding may fail imageWidthOdd = (imageSize[0] & 1 == 1) imageHeightOdd = (imageSize[1] & 1 == 1) if imageWidthOdd or imageHeightOdd: imageClipper = vtk.vtkImageClip() imageClipper.SetInputConnection(wti.GetOutputPort()) extent = outputImage.GetExtent() imageClipper.SetOutputWholeExtent( extent[0], extent[1] - 1 if imageWidthOdd else extent[1], extent[2], extent[3] - 1 if imageHeightOdd else extent[3], extent[4], extent[5]) writer.SetInputConnection(imageClipper.GetOutputPort()) else: writer.SetInputConnection(wti.GetOutputPort()) writer.Write()
def captureImageFromView(self, view, filename): view.forceRender() # qt.QPixmap().grabWidget(...) would not grab the background rw = view.renderWindow() wti = vtk.vtkWindowToImageFilter() wti.SetInput(rw) wti.Update() writer = vtk.vtkPNGWriter() writer.SetFileName(filename) outputImage = wti.GetOutput() imageSize = outputImage.GetDimensions() if imageSize[0]<2 or imageSize[1]<2: # image is too small, most likely it is invalid raise ValueError('Capture image from view failed') # Make sure image witdth and height is even, otherwise encoding may fail imageWidthOdd = (imageSize[0] & 1 == 1) imageHeightOdd = (imageSize[1] & 1 == 1) if imageWidthOdd or imageHeightOdd: imageClipper = vtk.vtkImageClip() imageClipper.SetInputConnection(wti.GetOutputPort()) extent = outputImage.GetExtent() imageClipper.SetOutputWholeExtent(extent[0], extent[1]-1 if imageWidthOdd else extent[1], extent[2], extent[3]-1 if imageHeightOdd else extent[3], extent[4], extent[5]) writer.SetInputConnection(imageClipper.GetOutputPort()) else: writer.SetInputConnection(wti.GetOutputPort()) writer.Write()
def BuildEditedImage(imagedata, points): """ Editing the original image in accordance with the edit points in the editor, it is necessary to generate the vtkPolyData via vtkContourFilter """ init_values = None for point in points: x, y, z = point colour = points[point] imagedata.SetScalarComponentFromDouble(x, y, z, 0, colour) imagedata.Update() if not (init_values): xi = x xf = x yi = y yf = y zi = z zf = z init_values = 1 if (xi > x): xi = x elif (xf < x): xf = x if (yi > y): yi = y elif (yf < y): yf = y if (zi > z): zi = z elif (zf < z): zf = z clip = vtk.vtkImageClip() clip.SetInput(imagedata) clip.SetOutputWholeExtent(xi, xf, yi, yf, zi, zf) clip.Update() gauss = vtk.vtkImageGaussianSmooth() gauss.SetInput(clip.GetOutput()) gauss.SetRadiusFactor(0.6) gauss.Update() app = vtk.vtkImageAppend() app.PreserveExtentsOn() app.SetAppendAxis(2) app.SetInput(0, imagedata) app.SetInput(1, gauss.GetOutput()) app.Update() return app.GetOutput()
def BuildEditedImage(imagedata, points): """ Editing the original image in accordance with the edit points in the editor, it is necessary to generate the vtkPolyData via vtkContourFilter """ init_values = None for point in points: x, y, z = point colour = points[point] imagedata.SetScalarComponentFromDouble(x, y, z, 0, colour) imagedata.Update() if not(init_values): xi = x xf = x yi = y yf = y zi = z zf = z init_values = 1 if (xi > x): xi = x elif(xf < x): xf = x if (yi > y): yi = y elif(yf < y): yf = y if (zi > z): zi = z elif(zf < z): zf = z clip = vtk.vtkImageClip() clip.SetInput(imagedata) clip.SetOutputWholeExtent(xi, xf, yi, yf, zi, zf) clip.Update() gauss = vtk.vtkImageGaussianSmooth() gauss.SetInput(clip.GetOutput()) gauss.SetRadiusFactor(0.6) gauss.Update() app = vtk.vtkImageAppend() app.PreserveExtentsOn() app.SetAppendAxis(2) app.SetInput(0, imagedata) app.SetInput(1, gauss.GetOutput()) app.Update() return app.GetOutput()
def RollMap( self, baseImage ): # baseImage.Update() if self.world_cut == self.map_cut: return baseImage baseExtent = baseImage.GetExtent() baseSpacing = baseImage.GetSpacing() x0 = baseExtent[0] x1 = baseExtent[1] newCut = self.NormalizeMapLon( self.world_cut ) delCut = newCut - self.map_cut # print " %%%%%% Roll Map %%%%%%: world_cut=%.1f, map_cut=%.1f, newCut=%.1f " % ( float(self.world_cut), float(self.map_cut), float(newCut) ) imageLen = x1 - x0 + 1 sliceSize = imageLen * ( delCut / 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent = list( baseExtent ) extent[0:2] = [ x0, x0 + sliceCoord - 1 ] clip0 = vtk.vtkImageClip() if vtk.VTK_MAJOR_VERSION <= 5: clip0.SetInput( baseImage ) else: clip0.SetInputData( baseImage ) clip0.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] ) extent[0:2] = [ x0 + sliceCoord, x1 ] clip1 = vtk.vtkImageClip() if vtk.VTK_MAJOR_VERSION <= 5: clip1.SetInput( baseImage ) else: clip1.SetInputData( baseImage ) clip1.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] ) append = vtk.vtkImageAppend() append.SetAppendAxis( 0 ) append.SetInputConnection ( clip1.GetOutputPort() ) append.AddInputConnection ( clip0.GetOutputPort() ) imageInfo = vtk.vtkImageChangeInformation() imageInfo.SetInputConnection( append.GetOutputPort() ) imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 ) imageInfo.SetOutputExtentStart( 0, 0, 0 ) imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] ) imageInfo.Update() result = imageInfo.GetOutput() return result
def RollMap(self, baseImage): baseImage.Update() if self.world_cut == self.map_cut: return baseImage baseExtent = baseImage.GetExtent() baseSpacing = baseImage.GetSpacing() x0 = baseExtent[0] x1 = baseExtent[1] newCut = NormalizeLon(self.world_cut) delCut = NormalizeLon(self.map_cut - newCut) imageLen = x1 - x0 + 1 sliceSize = imageLen * (delCut / 360.0) sliceCoord = int(round(x0 + sliceSize)) extent = list(baseExtent) extent[0:2] = [x0, x0 + sliceCoord - 1] clip0 = vtk.vtkImageClip() clip0.SetInput(baseImage) clip0.SetOutputWholeExtent(extent[0], extent[1], extent[2], extent[3], extent[4], extent[5]) extent[0:2] = [x0 + sliceCoord, x1] clip1 = vtk.vtkImageClip() clip1.SetInput(baseImage) clip1.SetOutputWholeExtent(extent[0], extent[1], extent[2], extent[3], extent[4], extent[5]) append = vtk.vtkImageAppend() append.SetAppendAxis(0) append.AddInput(clip1.GetOutput()) append.AddInput(clip0.GetOutput()) imageInfo = vtk.vtkImageChangeInformation() imageInfo.SetInputConnection(append.GetOutputPort()) imageInfo.SetOutputOrigin(0.0, 0.0, 0.0) imageInfo.SetOutputExtentStart(0, 0, 0) imageInfo.SetOutputSpacing(baseSpacing[0], baseSpacing[1], baseSpacing[2]) result = imageInfo.GetOutput() result.Update() return result
def clipImage(self, inputImage, maskExtent, margin): clipper = vtk.vtkImageClip() clipper.SetOutputWholeExtent(maskExtent[0] - margin[0], maskExtent[1] + margin[0], maskExtent[2] - margin[1], maskExtent[3] + margin[1], maskExtent[4] - margin[2], maskExtent[5] + margin[2]) clipper.SetInputData(inputImage) clipper.SetClipData(True) clipper.Update() clippedImage = slicer.vtkOrientedImageData() clippedImage.ShallowCopy(clipper.GetOutput()) clippedImage.CopyDirections(inputImage) return clippedImage
def RollMap( self, baseImage ): baseImage.Update() if self.world_cut == self.map_cut: return baseImage baseExtent = baseImage.GetExtent() baseSpacing = baseImage.GetSpacing() x0 = baseExtent[0] x1 = baseExtent[1] newCut = NormalizeLon( self.world_cut ) delCut = NormalizeLon( self.map_cut - newCut ) imageLen = x1 - x0 + 1 sliceSize = imageLen * ( delCut / 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent = list( baseExtent ) extent[0:2] = [ x0, x0 + sliceCoord - 1 ] clip0 = vtk.vtkImageClip() clip0.SetInput( baseImage ) clip0.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] ) extent[0:2] = [ x0 + sliceCoord, x1 ] clip1 = vtk.vtkImageClip() clip1.SetInput( baseImage ) clip1.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] ) append = vtk.vtkImageAppend() append.SetAppendAxis( 0 ) append.AddInput( clip1.GetOutput() ) append.AddInput( clip0.GetOutput() ) imageInfo = vtk.vtkImageChangeInformation() imageInfo.SetInputConnection( append.GetOutputPort() ) imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 ) imageInfo.SetOutputExtentStart( 0, 0, 0 ) imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] ) result = imageInfo.GetOutput() result.Update() return result
def SplitIntoSlices(vtkImage): vtkImageClip = vtk.vtkImageClip() vtkImageClip.SetInput(vtkImage) vtkImageClip.ClipDataOn() dimensions = vtkImage.GetDimensions() slices = [] for z in range(0, dimensions[2]): vtkImageClip.SetOutputWholeExtent(0, dimensions[0], 0, dimensions[1], z, z) slice = vtk.vtkImageData() vtkImageClip.Update() slice.DeepCopy(vtkImageClip.GetOutput()) slices.append(slice) del vtkImageClip return slices
def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._clipper = vtk.vtkImageClip() module_utils.setup_vtk_object_progress(self, self._clipper, 'Reading PNG images.') self._config.outputWholeExtent = (0,-1,0,-1,0,-1) configList = [ ('OutputWholeExtent:', 'outputWholeExtent', 'tuple:float,6', 'text', 'The size of the clip volume.')] ScriptedConfigModuleMixin.__init__(self, configList) self._viewFrame = self._createViewFrame( {'Module (self)' : self, 'vtkImageClip' : self._clipper}) self.config_to_logic() self.syncViewWithLogic()
def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._clipper = vtk.vtkImageClip() module_utils.setup_vtk_object_progress(self, self._clipper, 'Reading PNG images.') self._config.outputWholeExtent = (0, -1, 0, -1, 0, -1) configList = [('OutputWholeExtent:', 'outputWholeExtent', 'tuple:float,6', 'text', 'The size of the clip volume.') ] ScriptedConfigModuleMixin.__init__(self, configList) self._viewFrame = self._createViewFrame({ 'Module (self)': self, 'vtkImageClip': self._clipper }) self.config_to_logic() self.syncViewWithLogic()
def clipInput(self, extent): self.clipper = vtk.vtkImageClip() self.clipper.AddInput(self._input) self.clipper.SetOutputWholeExtent(extent)
renWin = vtk.vtkRenderWindow() renWin.SetMultiSamples(0) renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # create pipeline # PIECE = 0 NUMBER_OF_PIECES = 8 reader = vtk.vtkImageReader() reader.SetDataByteOrderToLittleEndian() reader.SetDataExtent(0,63,0,63,1,64) reader.SetFilePrefix("" + str(VTK_DATA_ROOT) + "/Data/headsq/quarter") reader.SetDataMask(0x7fff) reader.SetDataSpacing(1.6,1.6,1.5) clipper = vtk.vtkImageClip() clipper.SetInputConnection(reader.GetOutputPort()) clipper.SetOutputWholeExtent(30,36,30,36,30,36) clipper2 = vtk.vtkImageClip() clipper2.SetInputConnection(reader.GetOutputPort()) clipper2.SetOutputWholeExtent(30,36,30,36,30,36) tris = vtk.vtkDataSetTriangleFilter() tris.SetInputConnection(clipper.GetOutputPort()) tris2 = vtk.vtkDataSetTriangleFilter() tris2.SetInputConnection(clipper2.GetOutputPort()) geom = vtk.vtkGeometryFilter() geom.SetInputConnection(tris.GetOutputPort()) pf = vtk.vtkProgrammableFilter() pf.SetInputConnection(tris2.GetOutputPort()) def remove_ghosts(): input = pf.GetInput()
def getBoundedMap(self, baseImage, dataLocation, map_cut_size, map_border_size): baseImage.Update() baseExtent = baseImage.GetExtent() baseSpacing = baseImage.GetSpacing() x0 = baseExtent[0] x1 = baseExtent[1] y0 = baseExtent[2] y1 = baseExtent[3] imageLen = [x1 - x0 + 1, y1 - y0 + 1] selectionDim = [map_cut_size[0] / 2, map_cut_size[1] / 2] dataXLoc = dataLocation[0] imageInfo = vtk.vtkImageChangeInformation() dataYbounds = [ dataLocation[1] - selectionDim[1], dataLocation[1] + selectionDim[1] ] vertExtent = [y0, y1] bounded_dims = None if dataYbounds[0] > -90.0: yOffset = dataYbounds[0] + 90.0 extOffset = int(round((yOffset / 180.0) * imageLen[1])) vertExtent[0] = y0 + extOffset self.y0 = dataYbounds[0] if dataYbounds[1] < 90.0: yOffset = 90.0 - dataYbounds[1] extOffset = int(round((yOffset / 180.0) * imageLen[1])) vertExtent[1] = y1 - extOffset overlapsBorder = ( self.NormalizeMapLon(dataLocation[0] - selectionDim[0]) > self.NormalizeMapLon(dataLocation[0] + selectionDim[0])) if overlapsBorder: cut0 = self.NormalizeMapLon(dataXLoc + selectionDim[0]) sliceSize = imageLen[0] * ((cut0 - self.map_cut) / 360.0) sliceCoord = int(round(x0 + sliceSize)) extent = list(baseExtent) extent[0:2] = [x0, x0 + sliceCoord - 1] clip0 = vtk.vtkImageClip() clip0.SetInput(baseImage) clip0.SetOutputWholeExtent(extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5]) size0 = extent[1] - extent[0] + 1 self.x0 = dataLocation[0] - selectionDim[0] cut1 = self.NormalizeMapLon(self.x0) sliceSize = imageLen[0] * ((cut1 - self.map_cut) / 360.0) sliceCoord = int(round(x0 + sliceSize)) extent[0:2] = [x0 + sliceCoord, x1] clip1 = vtk.vtkImageClip() clip1.SetInput(baseImage) clip1.SetOutputWholeExtent(extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5]) size1 = extent[1] - extent[0] + 1 # print "Set Corner pos: %s, cuts: %s " % ( str(self.x0), str( (cut0, cut1) ) ) append = vtk.vtkImageAppend() append.SetAppendAxis(0) append.AddInput(clip1.GetOutput()) append.AddInput(clip0.GetOutput()) bounded_dims = (size0 + size1, vertExtent[1] - vertExtent[0] + 1) imageInfo.SetInputConnection(append.GetOutputPort()) else: self.x0 = dataXLoc - selectionDim[0] cut0 = self.NormalizeMapLon(self.x0) sliceSize = imageLen[0] * ((cut0 - self.map_cut) / 360.0) sliceCoord = int(round(x0 + sliceSize)) extent = list(baseExtent) extent[0] = x0 + sliceCoord - 1 cut1 = self.NormalizeMapLon(dataXLoc + selectionDim[0]) sliceSize = imageLen[0] * ((cut1 - self.map_cut) / 360.0) sliceCoord = int(round(x0 + sliceSize)) extent[1] = x0 + sliceCoord clip = vtk.vtkImageClip() clip.SetInput(baseImage) clip.SetOutputWholeExtent(extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5]) bounded_dims = (extent[1] - extent[0] + 1, vertExtent[1] - vertExtent[0] + 1) # print "Set Corner pos: %s, dataXLoc: %s " % ( str(self.x0), str( (dataXLoc, selectionDim[0]) ) ) imageInfo.SetInputConnection(clip.GetOutputPort()) imageInfo.SetOutputOrigin(0.0, 0.0, 0.0) imageInfo.SetOutputExtentStart(0, 0, 0) imageInfo.SetOutputSpacing(baseSpacing[0], baseSpacing[1], baseSpacing[2]) result = imageInfo.GetOutput() result.Update() return result, bounded_dims
def testimageMCAll(self): # Create the RenderWindow, Renderer and both Actors # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) # create pipeline # slc = vtk.vtkStructuredPointsReader() slc.SetFileName(VTK_DATA_ROOT + "/Data/ironProt.vtk") colors = [ "flesh", "banana", "grey", "pink", "carrot", "gainsboro", "tomato", "gold", "thistle", "chocolate" ] types = [ "UnsignedChar", "Char", "Short", "UnsignedShort", "Int", "UnsignedInt", "Long", "UnsignedLong", "Float", "Double" ] i = 1 c = 0 clip = list() cast = list() iso = list() mapper = list() actor = list() colorWrapper = self.Colors() for idx, vtkType in enumerate(types): clip.append(vtk.vtkImageClip()) clip[idx].SetInputConnection(slc.GetOutputPort()) clip[idx].SetOutputWholeExtent(-1000, 1000, -1000, 1000, i, i + 5) i += 5 cast.append(vtk.vtkImageCast()) eval('cast[idx].SetOutputScalarTypeTo' + vtkType + '()') cast[idx].SetInputConnection(clip[idx].GetOutputPort()) cast[idx].ClampOverflowOn() iso.append(vtk.vtkMarchingContourFilter()) iso[idx].SetInputConnection(cast[idx].GetOutputPort()) iso[idx].GenerateValues(1, 30, 30) mapper.append(vtk.vtkPolyDataMapper()) mapper[idx].SetInputConnection(iso[idx].GetOutputPort()) mapper[idx].ScalarVisibilityOff() actor.append(vtk.vtkActor()) actor[idx].SetMapper(mapper[idx]) # actor[idx].Actor.GetProperty().SetDiffuseColor(lindex.colors.c.lindex.colors.c+1.lindex.colors.c+1) actor[idx].GetProperty().SetDiffuseColor( colorWrapper.GetRGBColor(colors[c])) actor[idx].GetProperty().SetSpecularPower(30) actor[idx].GetProperty().SetDiffuse(.7) actor[idx].GetProperty().SetSpecular(.5) c += 1 ren.AddActor(actor[idx]) outline = vtk.vtkOutlineFilter() outline.SetInputConnection(slc.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineActor.VisibilityOff() # Add the actors to the renderer, set the background and size # ren.AddActor(outlineActor) ren.SetBackground(0.9, .9, .9) ren.ResetCamera() ren.GetActiveCamera().SetViewAngle(30) ren.GetActiveCamera().Elevation(20) ren.GetActiveCamera().Azimuth(20) ren.GetActiveCamera().Zoom(1.5) ren.ResetCameraClippingRange() renWin.SetSize(400, 400) # render and interact with data iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin) renWin.Render() img_file = "imageMCAll.png" vtk.test.Testing.compareImage( iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
def getBoundedMap(self, baseImage, dataLocation, map_cut_size): baseExtent = baseImage.GetExtent() baseSpacing = baseImage.GetSpacing() x0 = baseExtent[0] x1 = baseExtent[1] y0 = baseExtent[2] y1 = baseExtent[3] imageLen = [x1 - x0 + 1, y1 - y0 + 1] selectionDim = [map_cut_size[0] / 2, map_cut_size[1] / 2] dataXLoc = NormalizeLon(dataLocation[0]) imageInfo = vtk.vtkImageChangeInformation() dataYbounds = [ dataLocation[1] - selectionDim[1], dataLocation[1] + selectionDim[1] ] vertExtent = [y0, y1] bounded_dims = None if dataYbounds[0] > -90.0: yOffset = dataYbounds[0] + 90.0 extOffset = int(round((yOffset / 180.0) * imageLen[1])) vertExtent[0] = y0 + extOffset self.y0 = dataYbounds[0] if dataYbounds[1] < 90.0: yOffset = 90.0 - dataYbounds[1] extOffset = int(round((yOffset / 180.0) * imageLen[1])) vertExtent[1] = y1 - extOffset if ((dataXLoc > selectionDim[0]) and (dataXLoc < (360 - selectionDim[0]))): cut0 = dataXLoc - selectionDim[0] sliceSize = imageLen[0] * (cut0 / 360.0) sliceCoord = int(round(x0 + sliceSize)) extent = list(baseExtent) extent[0] = x0 + sliceCoord - 1 cut1 = dataXLoc + selectionDim[0] sliceSize = imageLen[0] * (cut1 / 360.0) sliceCoord = int(round(x0 + sliceSize)) extent[1] = x0 + sliceCoord clip = vtk.vtkImageClip() if vtk.VTK_MAJOR_VERSION <= 5: clip.SetInput(baseImage) else: clip.SetInputData(baseImage) clip.SetOutputWholeExtent(extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5]) self.x0 = cut0 bounded_dims = (extent[1] - extent[0] + 1, vertExtent[1] - vertExtent[0] + 1) imageInfo.SetInputConnection(clip.GetOutputPort()) else: cut0 = NormalizeLon(dataXLoc + selectionDim[0]) sliceSize = imageLen[0] * (cut0 / 360.0) sliceCoord = int(round(x0 + sliceSize)) extent = list(baseExtent) extent[0:2] = [x0, x0 + sliceCoord - 1] clip0 = vtk.vtkImageClip() if vtk.VTK_MAJOR_VERSION <= 5: clip0.SetInput(baseImage) else: clip0.SetInputData(baseImage) clip0.SetOutputWholeExtent(extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5]) size0 = extent[1] - extent[0] + 1 cut1 = NormalizeLon(dataLocation[0] - selectionDim[0]) sliceSize = imageLen[0] * (cut1 / 360.0) sliceCoord = int(round(x0 + sliceSize)) extent[0:2] = [x0 + sliceCoord, x1] clip1 = vtk.vtkImageClip() if vtk.VTK_MAJOR_VERSION <= 5: clip1.SetInput(baseImage) else: clip1.SetInputData(baseImage) clip1.SetOutputWholeExtent(extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5]) size1 = extent[1] - extent[0] + 1 self.x0 = cut1 append = vtk.vtkImageAppend() append.SetAppendAxis(0) append.AddInput(clip1.GetOutput()) append.AddInput(clip0.GetOutput()) bounded_dims = (size0 + size1, vertExtent[1] - vertExtent[0] + 1) imageInfo.SetInputConnection(append.GetOutputPort()) imageInfo.SetOutputOrigin(0.0, 0.0, 0.0) imageInfo.SetOutputExtentStart(0, 0, 0) imageInfo.SetOutputSpacing(baseSpacing[0], baseSpacing[1], baseSpacing[2]) imageInfo.Update() result = imageInfo.GetOutput() return result, bounded_dims
def captureImageFromView(self, view, filename): slicer.app.processEvents() if view: view.forceRender() else: # force rendering of all views lm = slicer.app.layoutManager() for viewIndex in range(lm.threeDViewCount): lm.threeDWidget(0).threeDView().forceRender() for sliceViewName in lm.sliceViewNames(): lm.sliceWidget(sliceViewName).sliceView().forceRender() if view is None: # no view is specified, capture the entire view layout # Simply using grabwidget on the view layout frame would grab the screen without background: # img = qt.QPixmap.grabWidget(slicer.app.layoutManager().viewport()) # Grab the main window and use only the viewport's area allViews = slicer.app.layoutManager().viewport() topLeft = allViews.mapTo(slicer.util.mainWindow(),allViews.rect.topLeft()) bottomRight = allViews.mapTo(slicer.util.mainWindow(),allViews.rect.bottomRight()) imageSize = bottomRight - topLeft if imageSize.x()<2 or imageSize.y()<2: # image is too small, most likely it is invalid raise ValueError('Capture image from view failed') # Make sure image witdth and height is even, otherwise encoding may fail if (imageSize.x() & 1 == 1): imageSize.setX(imageSize.x()-1) if (imageSize.y() & 1 == 1): imageSize.setY(imageSize.y()-1) img = qt.QPixmap.grabWidget(slicer.util.mainWindow(), topLeft.x(), topLeft.y(), imageSize.x(), imageSize.y()) img.save(filename) return rw = view.renderWindow() wti = vtk.vtkWindowToImageFilter() wti.SetInput(rw) wti.Update() writer = vtk.vtkPNGWriter() writer.SetFileName(filename) outputImage = wti.GetOutput() imageSize = outputImage.GetDimensions() if imageSize[0]<2 or imageSize[1]<2: # image is too small, most likely it is invalid raise ValueError('Capture image from view failed') # Make sure image witdth and height is even, otherwise encoding may fail imageWidthOdd = (imageSize[0] & 1 == 1) imageHeightOdd = (imageSize[1] & 1 == 1) if imageWidthOdd or imageHeightOdd: imageClipper = vtk.vtkImageClip() imageClipper.SetInputConnection(wti.GetOutputPort()) extent = outputImage.GetExtent() imageClipper.SetOutputWholeExtent(extent[0], extent[1]-1 if imageWidthOdd else extent[1], extent[2], extent[3]-1 if imageHeightOdd else extent[3], extent[4], extent[5]) writer.SetInputConnection(imageClipper.GetOutputPort()) else: writer.SetInputConnection(wti.GetOutputPort()) writer.Write()
def testContour2DAll(self): # Create the RenderWindow, Renderer and both Actors # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.SetMultiSamples(0) renWin.AddRenderer(ren) # create pipeline # slc = vtk.vtkSLCReader() slc.SetFileName(VTK_DATA_ROOT + "/Data/nut.slc") slc.Update() types = ["Char", "UnsignedChar", "Short", "UnsignedShort", "Int", "UnsignedInt", "Long", "UnsignedLong", "Float", "Double"] i = 3 clip = list() cast = list() iso = list() mapper = list() actor = list() for idx, vtkType in enumerate(types): clip.append(vtk.vtkImageClip()) clip[idx].SetInputConnection(slc.GetOutputPort()) clip[idx].SetOutputWholeExtent(-1000, 1000, -1000, 1000, i, i) i += 2 cast.append(vtk.vtkImageCast()) eval("cast[idx].SetOutputScalarTypeTo" + vtkType) cast[idx].SetInputConnection(clip[idx].GetOutputPort()) cast[idx].ClampOverflowOn() iso.append(vtk.vtkContourFilter()) iso[idx] = vtk.vtkContourFilter() iso[idx].SetInputConnection(cast[idx].GetOutputPort()) iso[idx].GenerateValues(1, 30, 30) mapper.append(vtk.vtkPolyDataMapper()) mapper[idx].SetInputConnection(iso[idx].GetOutputPort()) mapper[idx].SetColorModeToMapScalars() actor.append(vtk.vtkActor()) actor[idx].SetMapper(mapper[idx]) ren.AddActor(actor[idx]) outline = vtk.vtkOutlineFilter() outline.SetInputConnection(slc.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineActor.VisibilityOff() # # Add the actors to the renderer, set the background and size # ren.AddActor(outlineActor) ren.ResetCamera() ren.GetActiveCamera().SetViewAngle(30) ren.GetActiveCamera().Elevation(20) ren.GetActiveCamera().Azimuth(20) ren.GetActiveCamera().Zoom(1.5) ren.ResetCameraClippingRange() ren.SetBackground(0.9, .9, .9) renWin.SetSize(200, 200) # render and interact with data iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin); renWin.Render() img_file = "contour2DAll.png" vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
#!/usr/bin/env python import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # Image pipeline reader = vtk.vtkPNGReader() reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/fullhead15.png") clip = vtk.vtkImageClip() clip.SetInputConnection(reader.GetOutputPort()) clip.SetOutputWholeExtent(80, 230, 80, 230, 0, 0) clip.ClipDataOff() gradient = vtk.vtkImageGradientMagnitude() gradient.SetDimensionality(2) gradient.SetInputConnection(clip.GetOutputPort()) gradient.HandleBoundariesOff() slide = vtk.vtkImageChangeInformation() slide.SetInputConnection(gradient.GetOutputPort()) slide.SetExtentTranslation(-100, -100, 0) viewer = vtk.vtkImageViewer() viewer.SetInputConnection(slide.GetOutputPort()) viewer.SetColorWindow(-1000) viewer.SetColorLevel(500) viewer.Render() #skipping source # --- end of script --
def _BuildPipeline(self): """_BuildPipeline - Builds the visualization pipeline""" image = component.getUtility(ICurrentImage) # update image (VTK-6 compatible) image.Update() # image reslice object reslice = vtk.vtkImageReslice() reslice.SetInterpolationModeToCubic() reslice.ReleaseDataFlagOn() reslice.SetInputConnection(image.GetOutputPort()) if self._transform: reslice.SetTransform(self._transform) # get extents, spacings, etc in_extent = image.GetExtent() in_spacing = image.GetSpacing() in_origin = image.GetOrigin() # get stencil data stencil_data = image.GetStencilData() # Set image resample factor f = self.gui.m_sliderSurfaceQuality.GetValue() / 100.0 if f == 0.0: f = 0.001 # Set surface decimation factor decf = self.gui.m_sliderDecimationFactor.GetValue() / 100.0 # Enable/Disable stencil usage if self.gui.m_checkBoxClipping.GetValue() is True and stencil_data: if vtk.vtkVersion().GetVTKMajorVersion() > 5: reslice.SetStencilData(stencil_data) else: reslice.SetStencil(stencil_data) reslice.SetBackgroundLevel(image.GetScalarRange()[0]) ext = stencil_data.GetExtent() else: ext = in_extent if vtk.vtkVersion().GetVTKMajorVersion() > 5: reslice.SetStencilData(None) else: reslice.SetStencil(None) # expand extent slightly - account for downsampling later too fudge = int(math.ceil(1.0 / f)) ext = [ext[0] - fudge, ext[1] + fudge, ext[2] - fudge, ext[3] + fudge, ext[4] - fudge, ext[5] + fudge] reslice.SetOutputExtent(ext) # set default origin/spacing -- these two lines work... reslice.SetOutputSpacing(in_spacing) reslice.SetOutputOrigin(in_origin) # do we need to downsample the image? if f < 1.0: resample = vtk.vtkImageResample() resample.SetInputConnection(reslice.GetOutputPort()) resample.ReleaseDataFlagOn() for i in range(3): resample.SetAxisMagnificationFactor(i, f) obj = resample else: obj = reslice # do we need to smooth the image? if self.gui.m_checkBoxImageSmoothing.GetValue() == True: smooth = vtk.vtkImageGaussianSmooth() smooth.SetStandardDeviation(1.0) smooth.ReleaseDataFlagOn() smooth.SetInputConnection(obj.GetOutputPort()) obj = smooth clip = vtk.vtkImageClip() clip.SetInputConnection(obj.GetOutputPort()) # setup contour filter cf = vtk.vtkMarchingCubes() cf.SetNumberOfContours(1) val = float(self.gui.m_textCtrlImageThreshold.GetValue()) cf.SetValue(0, val) cf.SetComputeScalars(0) cf.SetComputeNormals(0) cf.SetInputConnection(clip.GetOutputPort()) # decimate surface decimate = vtk.vtkDecimatePro() decimate.SetInputConnection(cf.GetOutputPort()) decimate.PreserveTopologyOn() decimate.SetTargetReduction(decf) # To cut down on memory consumption, we use the clip object # to process the image a chunk at a time. By default we # use 20 chunks -- but if the chunks are too small, we'll adjust this # number clip.UpdateInformation() ext = clip.GetInput().GetExtent() # main processing loop with wx.BusyCursor(): event.notify(ProgressEvent("Generating surface...", 0.0)) clip.SetOutputWholeExtent(ext[0], ext[1], ext[2], ext[3], ext[4], ext[5]) decimate.Update() event.notify(ProgressEvent("Generating surface...", 1.0)) # Create the rendered Geometry if not self._app_states[self._current_image_index].GetFactory(): self._app_states[self._current_image_index].SetFactory( vtkAtamai.SurfaceObjectFactory.SurfaceObjectFactory() ) self._app_states[self._current_image_index].GetFactory().SetInputConnection(decimate.GetOutputPort()) self._app_states[self._current_image_index].GetFactory().SetBackfaceProperty( self._app_states[self._current_image_index].GetFactory().GetProperty() ) self._app_states[self._current_image_index].GetFactory().NormalGenerationOn() self.SetSurfaceColor() self.GetMicroView().pane3D.ConnectActorFactory(self._app_states[self._current_image_index].GetFactory()) self._app_states[self._current_image_index]._disconnected = False # Update math values self.UpdateMathValues()
def testContour3DAll(self): # On older Macs, 10 is too low. Due to what looks like a driver bug # spectral lighting behaves sort of weird and produces small differences threshold = 30 # Create the RenderWindow, Renderer and both Actors # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) # create pipeline # slc = vtk.vtkStructuredPointsReader() slc.SetFileName(VTK_DATA_ROOT + "/Data/ironProt.vtk") actorColors = ["flesh", "banana", "grey", "pink", "carrot", "gainsboro", "tomato", "gold", "thistle", "chocolate"] types = ["UnsignedChar", "Char", "Short", "UnsignedShort", "Int", "UnsignedInt", "Long", "UnsignedLong", "Float", "Double"] i = 1 c = 0 clip = list() cast = list() iso = list() mapper = list() actor = list() colors = self.Colors() for idx, vtkType in enumerate(types): clip.append(vtk.vtkImageClip()) clip[idx].SetInputConnection(slc.GetOutputPort()) clip[idx].SetOutputWholeExtent(-1000, 1000, -1000, 1000, i, i + 5) i += 5 cast.append(vtk.vtkImageCast()) eval("cast[idx].SetOutputScalarTypeTo" + vtkType) cast[idx].SetInputConnection(clip[idx].GetOutputPort()) cast[idx].ClampOverflowOn() iso.append(vtk.vtkContourFilter()) iso[idx].SetInputConnection(cast[idx].GetOutputPort()) iso[idx].GenerateValues(1, 30, 30) iso[idx].ComputeScalarsOff() iso[idx].ComputeGradientsOff() mapper.append(vtk.vtkPolyDataMapper()) mapper[idx].SetInputConnection(iso[idx].GetOutputPort()) mapper[idx].ImmediateModeRenderingOn() actor.append(vtk.vtkActor()) actor[idx].SetMapper(mapper[idx]) eval('actor[idx].GetProperty().SetDiffuseColor(colors.GetRGBColor("' + actorColors[idx] + '"))') actor[idx].GetProperty().SetSpecularPower(30) actor[idx].GetProperty().SetDiffuse(.7) actor[idx].GetProperty().SetSpecular(.5) c += 3 ren.AddActor(actor[idx]) outline = vtk.vtkOutlineFilter() outline.SetInputConnection(slc.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineActor.VisibilityOff() # Add the actors to the renderer, set the background and size # ren.AddActor(outlineActor) ren.SetBackground(0.9, .9, .9) ren.ResetCamera() ren.GetActiveCamera().SetViewAngle(30) ren.GetActiveCamera().Elevation(20) ren.GetActiveCamera().Azimuth(20) ren.GetActiveCamera().Zoom(1.5) ren.ResetCameraClippingRange() renWin.SetSize(400, 400) # render and interact with data iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin); renWin.Render() img_file = "contour3DAll.png" vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
def clipInput(self, extent): self.clipper = vtk.vtkImageClip() if vtk.VTK_MAJOR_VERSION <= 5: self.clipper.AddInput(self._input) else: self.clipper.AddInputData(self._input) self.clipper.SetOutputWholeExtent(extent)
def clipInput( self, extent ): self.clipper = vtk.vtkImageClip() if vtk.VTK_MAJOR_VERSION <= 5: self.clipper.AddInput( self._input ) else: self.clipper.AddInputData( self._input ) self.clipper.SetOutputWholeExtent( extent )
def VTKConvolve(im,numret=0,k=5,clip=1,x=1,y=1,wrap=0,mirror=1,constant=None, kernel=None): if type(im) == np.ndarray: i = NumToVTKImage(im) else: i = im d = i.GetDimensions() e = i.GetExtent() dtest = np.sort(d) if sum(dtest[:2]) == 2: onedim=1 else: onedim = 0 if (d[0] == 1): oned = 1 elif (d[1] == 1): oned = 2 else: oned = 0 if x and not y: oned = 2 if y and not x: oned = 1 if onedim: oned = 1 if constant is not None: ip = vtk.vtkImageConstantPad() if d[0] > 1: x0,x1=-k,d[0]+k-1 else: x0,x1=0,0 if d[1] > 1: y0,y1=-k,d[1]+k-1 else: y0,y1=0,0 ip.SetOutputWholeExtent(x0,x1,y0,y1,0,0) ip.SetConstant(constant) ip.SetInputData(i) i = ip.GetOutput() ip.Update() elif mirror: ip = vtk.vtkImageMirrorPad() if d[0] > 1: x0,x1=-k,d[0]+k-1 else: x0,x1=0,0 if d[1] > 1: y0,y1=-k,d[1]+k-1 else: y0,y1=0,0 ip.SetOutputWholeExtent(x0,x1,y0,y1,0,0) ip.SetInputData(i) i = ip.GetOutput() ip.Update() elif wrap: ip = vtk.vtkImageWrapPad() if d[0] > 1: x0,x1=-k,d[0]+k-1 else: x0,x1=0,0 if d[1] > 1: y0,y1=-k,d[1]+k-1 else: y0,y1=0,0 ip.SetOutputWholeExtent(x0,x1,y0,y1,0,0) ip.SetInputData(i) i = ip.GetOutput() ip.Update() c = vtk.vtkImageConvolve() if kernel is None: if k == 3: k1 = np.asarray([0.25,0.5,0.25]) elif k == 5: k1 = np.asarray([0.0625,0.25,0.375,0.25,0.0625]) if onedim: ke = np.ones((k,k),np.float64) * k1 elif not oned: ke = k1[::,np.newaxis]*k1[np.newaxis,::] elif oned == 1: ke = np.zeros((k,k),np.float64); ke[::,2] = k1 elif oned == 2: ke = np.zeros((k,k),np.float64); ke[2] = k1 ke = np.ravel(ke) ke = ke / np.sum(ke) if onedim: ke = len(k1)*ke else: k = kernel.shape[0] ke = np.ravel(kernel) if k == 3: c.SetKernel3x3(ke) if k == 5: c.SetKernel5x5(ke) if k == 7: c.SetKernel7x7(ke) c.SetInputData(i) o = c.GetOutput() c.Update() if clip: ic = vtk.vtkImageClip() notx = -(not x) * 0 noty = -(not y) * 0 ic.SetOutputWholeExtent(notx,d[0]-1+notx,noty,d[1]-1+noty,0,0) ic.SetInputData(o) ic.ClipDataOn() o = ic.GetOutput() ic.Update() if numret: return VTKImageToNum(o) else: return o
from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # Simple example that used to crash when an UpdateExtent request # from one algorithm is overwritten by a smaller UpdateExtent # request from another algorithm. The COMBINED_UPDATE_EXTENT # key was added to vtkStreamingDemandDrivenPipeline to fix the # bug that caused the crash. # read an image that has an extent of 0 255 0 255 0 0 reader = vtk.vtkPNGReader() reader.SetDataSpacing(0.8,0.8,1.5) reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/fullhead15.png") # Uncomment this to make the crash disappear #reader Update # clip the image down to 0 127 0 127 0 0 clip = vtk.vtkImageClip() clip.SetInputConnection(reader.GetOutputPort()) clip.SetOutputWholeExtent(0,127,0,127,0,0) # darken the background darken = vtk.vtkImageShiftScale() darken.SetInputConnection(reader.GetOutputPort()) darken.SetScale(0.2) # do an operation on the clipped and unclipped data blend = vtk.vtkImageBlend() blend.SetInputConnection(darken.GetOutputPort()) blend.AddInputConnection(clip.GetOutputPort()) viewer = vtk.vtkImageViewer() viewer.SetInputConnection(blend.GetOutputPort()) viewer.SetColorWindow(2000) viewer.SetColorLevel(1000) viewer.Render()
def Execute(self): if self.GaussFiltering: gauss = vtk.vtkImageGaussianSmooth() gauss.SetInput(self.Image) gauss.SetStandardDeviations(self.StandardDeviations) gauss.SetRadiusFactors(self.RadiusFactors) if self.Shape.find('2d') != -1: gauss.SetDimensionality(2) elif self.Shape.find('3d') != -1: gauss.SetDimensionality(3) else: gauss.SetDimensionality(3) gauss.Update() self.Image = gauss.GetOutput() scalarRange = [0.0,0.0] if self.FWHMRegion == 'image': scalarRange = self.Image.GetScalarRange() elif self.FWHMRegion == 'midline': extent = self.Image.GetWholeExtent() newYExtent = extent[2]+(extent[3]-extent[2])/2 clip = vtk.vtkImageClip() clip.SetInput(self.Image) clip.SetOutputWholeExtent(extent[0],extent[1],newYExtent,newYExtent,extent[4],extent[5]) clip.ClipDataOn() clip.Update() scalarRange = clip.GetOutput().GetScalarRange() self.FWHMLevel = (scalarRange[1] - scalarRange[0]) * self.FWHMRatio + scalarRange[0] if self.FWHMBackground != None: self.FWHMLevel = (scalarRange[1] - self.FWHMBackground) * self.FWHMRatio + self.FWHMBackground if self.Method == 'levelsets': if self.Shape.find('2d') != -1: gradientMagnitude = vtk.vtkImageGradientMagnitude() gradientMagnitude.SetDimensionality(2) elif self.Shape.find('3d') != -1: if self.FeatureImageType == 'gradient': gradientMagnitude = vtkvmtk.vtkvmtkGradientMagnitudeImageFilter() elif self.FeatureImageType == 'upwind': gradientMagnitude = vtkvmtk.vtkvmtkUpwindGradientMagnitudeImageFilter() gradientMagnitude.SetUpwindFactor(self.UpwindFactor) else: self.PrintError('Unsupported feature image type: choices are "gradient", "upwind".') return else: gradientMagnitude = vtk.vtkImageGradientMagnitude() gradientMagnitude.SetInput(self.Image) gradientMagnitude.Update() boundedReciprocal = vtkvmtk.vtkvmtkBoundedReciprocalImageFilter() boundedReciprocal.SetInput(gradientMagnitude.GetOutput()) boundedReciprocal.Update() self.FeatureImage = vtk.vtkImageData() self.FeatureImage.DeepCopy(boundedReciprocal.GetOutput()) levelSetsFilter = None if self.Shape.find('2d') != -1: levelSetsFilter = vtkvmtk.vtkvmtkGeodesicActiveContourLevelSet2DImageFilter() elif self.Shape.find('3d') != -1: levelSetsFilter = vtkvmtk.vtkvmtkGeodesicActiveContourLevelSetImageFilter() else: levelSetsFilter = vtkvmtk.vtkvmtkGeodesicActiveContourLevelSetImageFilter() levelSetsFilter.SetInput(self.Image) levelSetsFilter.SetFeatureImage(boundedReciprocal.GetOutput()) levelSetsFilter.SetDerivativeSigma(0.0) levelSetsFilter.SetAutoGenerateSpeedAdvection(1) levelSetsFilter.SetNumberOfIterations(self.LevelSetsIterations) levelSetsFilter.SetPropagationScaling(0.0) levelSetsFilter.SetCurvatureScaling(self.CurvatureScaling) levelSetsFilter.SetAdvectionScaling(1.0) levelSetsFilter.SetIsoSurfaceValue(self.FWHMLevel) levelSetsFilter.SetInterpolateSurfaceLocation(1) levelSetsFilter.SetMaximumRMSError(1E-10) levelSetsFilter.Update() self.LevelSets = vtk.vtkImageData() self.LevelSets.DeepCopy(levelSetsFilter.GetOutput()) contourFilter = vtk.vtkMarchingContourFilter() contourFilter.SetInput(self.LevelSets) contourFilter.SetValue(0,0.0) contourFilter.Update() self.Contour = contourFilter.GetOutput() elif self.Method == 'fwhm': contourFilter = vtk.vtkMarchingContourFilter() contourFilter.SetInput(self.Image) contourFilter.SetValue(0,self.FWHMLevel) contourFilter.Update() self.Contour = contourFilter.GetOutput() else: self.PrintError('Unsupported method: choices are "levelsets", "fwhm".') return if self.Smoothing: smoothingFilter = vtk.vtkWindowedSincPolyDataFilter() smoothingFilter.SetInput(self.Contour) smoothingFilter.SetNumberOfIterations(self.SmoothingIterations) smoothingFilter.SetPassBand(self.SmoothingPassBand) smoothingFilter.Update() self.Contour = smoothingFilter.GetOutput() measurementFilter = None if self.Shape is 'thickplane2d': measurementFilter = femri2DPlaneThickness() elif self.Shape is 'cylinder2d': measurementFilter = femri2DCylinderThickness() elif self.Shape is 'hollowcylinder2d': measurementFilter = femri2DHollowCylinderThickness() elif self.Shape is 'cylinder3d': measurementFilter = femri3DCylinderThickness() else: self.PrintError('Unsupported shape: choices are "thickplane2d", "cylinder2d", "hollowcylinder2d", "cylinder3d".') return measurementFilter.Contour = self.Contour measurementFilter.Center = self.Center measurementFilter.TiltingAngle = math.radians(self.TiltingAngle) measurementFilter.RotationAngle = math.radians(self.RotationAngle) measurementFilter.Execute() if self.Shape is 'hollowcylinder2d': measurementFilter.ComputeAreas() self.InnerArea = measurementFilter.InnerArea self.OuterArea = measurementFilter.OuterArea self.Thickness = measurementFilter.Thickness self.Thickness3D = measurementFilter.Thickness3D self.Locations = measurementFilter.Locations self.Contour = measurementFilter.Contour self.OutputText('\n') self.OutputText('Thickness: ' + str(self.Thickness) + '\n') self.OutputText('Thickness3D: ' + str(self.Thickness3D) + '\n') self.OutputText('Locations: ' + str(self.Locations) + '\n') if self.Shape is 'hollowcylinder2d': self.OutputText('InnerArea: ' + str(self.InnerArea) + '\n') self.OutputText('OuterArea: ' + str(self.OuterArea) + '\n') self.OutputText('\n')
def testContour2DAll(self): # Create the RenderWindow, Renderer and both Actors # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.SetMultiSamples(0) renWin.AddRenderer(ren) # create pipeline # slc = vtk.vtkSLCReader() slc.SetFileName(VTK_DATA_ROOT + "/Data/nut.slc") slc.Update() types = [ "Char", "UnsignedChar", "Short", "UnsignedShort", "Int", "UnsignedInt", "Long", "UnsignedLong", "Float", "Double" ] i = 3 clip = list() cast = list() iso = list() mapper = list() actor = list() for idx, vtkType in enumerate(types): clip.append(vtk.vtkImageClip()) clip[idx].SetInputConnection(slc.GetOutputPort()) clip[idx].SetOutputWholeExtent(-1000, 1000, -1000, 1000, i, i) i += 2 cast.append(vtk.vtkImageCast()) eval("cast[idx].SetOutputScalarTypeTo" + vtkType) cast[idx].SetInputConnection(clip[idx].GetOutputPort()) cast[idx].ClampOverflowOn() iso.append(vtk.vtkContourFilter()) iso[idx] = vtk.vtkContourFilter() iso[idx].SetInputConnection(cast[idx].GetOutputPort()) iso[idx].GenerateValues(1, 30, 30) mapper.append(vtk.vtkPolyDataMapper()) mapper[idx].SetInputConnection(iso[idx].GetOutputPort()) mapper[idx].SetColorModeToMapScalars() actor.append(vtk.vtkActor()) actor[idx].SetMapper(mapper[idx]) ren.AddActor(actor[idx]) outline = vtk.vtkOutlineFilter() outline.SetInputConnection(slc.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineActor.VisibilityOff() # # Add the actors to the renderer, set the background and size # ren.AddActor(outlineActor) ren.ResetCamera() ren.GetActiveCamera().SetViewAngle(30) ren.GetActiveCamera().Elevation(20) ren.GetActiveCamera().Azimuth(20) ren.GetActiveCamera().Zoom(1.5) ren.ResetCameraClippingRange() ren.SetBackground(0.9, .9, .9) renWin.SetSize(200, 200) # render and interact with data iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin) renWin.Render() img_file = "contour2DAll.png" vtk.test.Testing.compareImage( iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
def addSequenceFromImageData(self, imageData, tempFrameVolume, filePath, name, singleFileInLoadable): # Rotate 180deg, otherwise the image would appear upside down ijkToRas = vtk.vtkMatrix4x4() ijkToRas.SetElement(0, 0, -1.0) ijkToRas.SetElement(1, 1, -1.0) tempFrameVolume.SetIJKToRASMatrix(ijkToRas) # z axis is time [spacingX, spacingY, frameTimeMsec] = imageData.GetSpacing() imageData.SetSpacing(1.0, 1.0, 1.0) tempFrameVolume.SetSpacing(spacingX, spacingY, 1.0) # Create new sequence outputSequenceNode = slicer.mrmlScene.AddNewNodeByClass( "vtkMRMLSequenceNode") # Get sequence name if singleFileInLoadable: outputSequenceNode.SetName(name) else: ds = dicom.read_file(filePath, stop_before_pixels=True) if hasattr(ds, 'PositionerPrimaryAngle') and hasattr( ds, 'PositionerSecondaryAngle'): outputSequenceNode.SetName( f'{name} ({ds.PositionerPrimaryAngle}/{ds.PositionerSecondaryAngle})' ) else: outputSequenceNode.SetName(name) if frameTimeMsec == 1.0: # frame time is not found, set it to 1.0fps frameTime = 1 outputSequenceNode.SetIndexName("frame") outputSequenceNode.SetIndexUnit("") playbackRateFps = 10 else: # frame time is set, use it frameTime = frameTimeMsec * 0.001 outputSequenceNode.SetIndexName("time") outputSequenceNode.SetIndexUnit("s") playbackRateFps = 1.0 / frameTime # Add frames to the sequence numberOfFrames = imageData.GetDimensions()[2] extent = imageData.GetExtent() numberOfFrames = extent[5] - extent[4] + 1 for frame in range(numberOfFrames): # get current frame from multiframe crop = vtk.vtkImageClip() crop.SetInputData(imageData) crop.SetOutputWholeExtent(extent[0], extent[1], extent[2], extent[3], extent[4] + frame, extent[4] + frame) crop.ClipDataOn() crop.Update() croppedOutput = crop.GetOutput() croppedOutput.SetExtent(extent[0], extent[1], extent[2], extent[3], 0, 0) croppedOutput.SetOrigin(0.0, 0.0, 0.0) tempFrameVolume.SetAndObserveImageData(croppedOutput) # get timestamp if type(frameTime) == int: timeStampSec = str(frame * frameTime) else: timeStampSec = f"{frame * frameTime:.3f}" outputSequenceNode.SetDataNodeAtValue(tempFrameVolume, timeStampSec) # Create storage node that allows saving node as nrrd outputSequenceStorageNode = slicer.vtkMRMLVolumeSequenceStorageNode() slicer.mrmlScene.AddNode(outputSequenceStorageNode) outputSequenceNode.SetAndObserveStorageNodeID( outputSequenceStorageNode.GetID()) return outputSequenceNode, playbackRateFps
def getBoundedMap( self, baseImage, dataLocation, map_cut_size ): baseImage.Update() baseExtent = baseImage.GetExtent() baseSpacing = baseImage.GetSpacing() x0 = baseExtent[0] x1 = baseExtent[1] y0 = baseExtent[2] y1 = baseExtent[3] imageLen = [ x1 - x0 + 1, y1 - y0 + 1 ] selectionDim = [ map_cut_size[0]/2, map_cut_size[1]/2 ] dataXLoc = NormalizeLon( dataLocation[0] ) imageInfo = vtk.vtkImageChangeInformation() dataYbounds = [ dataLocation[1]-selectionDim[1], dataLocation[1]+selectionDim[1] ] vertExtent = [ y0, y1 ] bounded_dims = None if dataYbounds[0] > -90.0: yOffset = dataYbounds[0] + 90.0 extOffset = int( round( ( yOffset / 180.0 ) * imageLen[1] ) ) vertExtent[0] = y0 + extOffset self.y0 = dataYbounds[0] if dataYbounds[1] < 90.0: yOffset = 90.0 - dataYbounds[1] extOffset = int( round( ( yOffset / 180.0 ) * imageLen[1] ) ) vertExtent[1] = y1 - extOffset if (( dataXLoc > selectionDim[0] ) and ( dataXLoc < ( 360 - selectionDim[0]) )): cut0 = dataXLoc - selectionDim[0] sliceSize = imageLen[0] * ( cut0 / 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent = list( baseExtent ) extent[0] = x0 + sliceCoord - 1 cut1 = dataXLoc + selectionDim[0] sliceSize = imageLen[0] * ( cut1 / 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent[1] = x0 + sliceCoord clip = vtk.vtkImageClip() clip.SetInput( baseImage ) clip.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] ) self.x0 = cut0 bounded_dims = ( extent[1] - extent[0] + 1, vertExtent[1] - vertExtent[0] + 1 ) imageInfo.SetInputConnection( clip.GetOutputPort() ) else: cut0 = NormalizeLon( dataXLoc + selectionDim[0] ) sliceSize = imageLen[0] * ( cut0 / 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent = list( baseExtent ) extent[0:2] = [ x0, x0 + sliceCoord - 1 ] clip0 = vtk.vtkImageClip() clip0.SetInput( baseImage ) clip0.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] ) size0 = extent[1] - extent[0] + 1 cut1 = NormalizeLon( dataLocation[0] - selectionDim[0] ) sliceSize = imageLen[0] * ( cut1 / 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent[0:2] = [ x0 + sliceCoord, x1 ] clip1 = vtk.vtkImageClip() clip1.SetInput( baseImage ) clip1.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] ) size1 = extent[1] - extent[0] + 1 self.x0 = cut1 append = vtk.vtkImageAppend() append.SetAppendAxis( 0 ) append.AddInput( clip1.GetOutput() ) append.AddInput( clip0.GetOutput() ) bounded_dims = ( size0 + size1, vertExtent[1] - vertExtent[0] + 1 ) imageInfo.SetInputConnection( append.GetOutputPort() ) imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 ) imageInfo.SetOutputExtentStart( 0, 0, 0 ) imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] ) result = imageInfo.GetOutput() result.Update() return result, bounded_dims
def testContour3DAll(self): # On older Macs, 10 is too low. Due to what looks like a driver bug # spectral lighting behaves sort of weird and produces small differences threshold = 30 # Create the RenderWindow, Renderer and both Actors # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) # create pipeline # slc = vtk.vtkStructuredPointsReader() slc.SetFileName(VTK_DATA_ROOT + "/Data/ironProt.vtk") actorColors = [ "flesh", "banana", "grey", "pink", "carrot", "gainsboro", "tomato", "gold", "thistle", "chocolate" ] types = [ "UnsignedChar", "Char", "Short", "UnsignedShort", "Int", "UnsignedInt", "Long", "UnsignedLong", "Float", "Double" ] i = 1 c = 0 clip = list() cast = list() iso = list() mapper = list() actor = list() colors = self.Colors() for idx, vtkType in enumerate(types): clip.append(vtk.vtkImageClip()) clip[idx].SetInputConnection(slc.GetOutputPort()) clip[idx].SetOutputWholeExtent(-1000, 1000, -1000, 1000, i, i + 5) i += 5 cast.append(vtk.vtkImageCast()) eval("cast[idx].SetOutputScalarTypeTo" + vtkType) cast[idx].SetInputConnection(clip[idx].GetOutputPort()) cast[idx].ClampOverflowOn() iso.append(vtk.vtkContourFilter()) iso[idx].SetInputConnection(cast[idx].GetOutputPort()) iso[idx].GenerateValues(1, 30, 30) iso[idx].ComputeScalarsOff() iso[idx].ComputeGradientsOff() mapper.append(vtk.vtkPolyDataMapper()) mapper[idx].SetInputConnection(iso[idx].GetOutputPort()) mapper[idx].ImmediateModeRenderingOn() actor.append(vtk.vtkActor()) actor[idx].SetMapper(mapper[idx]) eval( 'actor[idx].GetProperty().SetDiffuseColor(colors.GetRGBColor("' + actorColors[idx] + '"))') actor[idx].GetProperty().SetSpecularPower(30) actor[idx].GetProperty().SetDiffuse(.7) actor[idx].GetProperty().SetSpecular(.5) c += 3 ren.AddActor(actor[idx]) outline = vtk.vtkOutlineFilter() outline.SetInputConnection(slc.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineActor.VisibilityOff() # Add the actors to the renderer, set the background and size # ren.AddActor(outlineActor) ren.SetBackground(0.9, .9, .9) ren.ResetCamera() ren.GetActiveCamera().SetViewAngle(30) ren.GetActiveCamera().Elevation(20) ren.GetActiveCamera().Azimuth(20) ren.GetActiveCamera().Zoom(1.5) ren.ResetCameraClippingRange() renWin.SetSize(400, 400) # render and interact with data iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin) renWin.Render() img_file = "contour3DAll.png" vtk.test.Testing.compareImage( iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
def testimageMCAll(self): # Create the RenderWindow, Renderer and both Actors # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) # create pipeline # slc = vtk.vtkStructuredPointsReader() slc.SetFileName(VTK_DATA_ROOT + "/Data/ironProt.vtk") colors = ["flesh", "banana", "grey", "pink", "carrot", "gainsboro", "tomato", "gold", "thistle", "chocolate"] types = ["UnsignedChar", "Char", "Short", "UnsignedShort", "Int", "UnsignedInt", "Long", "UnsignedLong", "Float", "Double"] i = 1 c = 0 clip = list() cast = list() iso = list() mapper = list() actor = list() colorWrapper = self.Colors() for idx, vtkType in enumerate(types): clip.append(vtk.vtkImageClip()) clip[idx].SetInputConnection(slc.GetOutputPort()) clip[idx].SetOutputWholeExtent(-1000, 1000, -1000, 1000, i, i + 5) i += 5 cast.append(vtk.vtkImageCast()) eval('cast[idx].SetOutputScalarTypeTo' + vtkType + '()') cast[idx].SetInputConnection(clip[idx].GetOutputPort()) cast[idx].ClampOverflowOn() iso.append(vtk.vtkMarchingContourFilter()) iso[idx].SetInputConnection(cast[idx].GetOutputPort()) iso[idx].GenerateValues(1, 30, 30) mapper.append(vtk.vtkPolyDataMapper()) mapper[idx].SetInputConnection(iso[idx].GetOutputPort()) mapper[idx].ScalarVisibilityOff() actor.append(vtk.vtkActor()) actor[idx].SetMapper(mapper[idx]) # actor[idx].Actor.GetProperty().SetDiffuseColor(lindex.colors.c.lindex.colors.c+1.lindex.colors.c+1) actor[idx].GetProperty().SetDiffuseColor(colorWrapper.GetRGBColor(colors[c])) actor[idx].GetProperty().SetSpecularPower(30) actor[idx].GetProperty().SetDiffuse(.7) actor[idx].GetProperty().SetSpecular(.5) c += 1 ren.AddActor(actor[idx]) outline = vtk.vtkOutlineFilter() outline.SetInputConnection(slc.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineActor.VisibilityOff() # Add the actors to the renderer, set the background and size # ren.AddActor(outlineActor) ren.SetBackground(0.9, .9, .9) ren.ResetCamera() ren.GetActiveCamera().SetViewAngle(30) ren.GetActiveCamera().Elevation(20) ren.GetActiveCamera().Azimuth(20) ren.GetActiveCamera().Zoom(1.5) ren.ResetCameraClippingRange() renWin.SetSize(400, 400) # render and interact with data iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin); renWin.Render() img_file = "imageMCAll.png" vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
def clipInput( self, extent ): self.clipper = vtk.vtkImageClip() self.clipper.AddInput( self._input ) self.clipper.SetOutputWholeExtent( extent )
def getBoundedMap( self, baseImage, dataLocation ): # print " @@@ MapManager: getBoundedMap " baseExtent = baseImage.GetExtent() baseSpacing = baseImage.GetSpacing() x0 = baseExtent[0] x1 = baseExtent[1] y0 = baseExtent[2] y1 = baseExtent[3] imageLen = [ x1 - x0 + 1, y1 - y0 + 1 ] selectionDim = [ self.map_cut_size[0]/2, self.map_cut_size[1]/2 ] dataXLoc = dataLocation[0] imageInfo = vtk.vtkImageChangeInformation() dataYbounds = [ dataLocation[1]-selectionDim[1], dataLocation[1]+selectionDim[1] ] vertExtent = [ y0, y1 ] bounded_dims = None if dataYbounds[0] > -90.0: yOffset = dataYbounds[0] + 90.0 extOffset = int( round( ( yOffset / 180.0 ) * imageLen[1] ) ) vertExtent[0] = y0 + extOffset self.y0 = dataYbounds[0] if dataYbounds[1] < 90.0: yOffset = 90.0 - dataYbounds[1] extOffset = int( round( ( yOffset / 180.0 ) * imageLen[1] ) ) vertExtent[1] = y1 - extOffset overlapsBorder = ( self.NormalizeMapLon(dataLocation[0]-selectionDim[0]) > self.NormalizeMapLon(dataLocation[0]+selectionDim[0]) ) if overlapsBorder: cut0 = self.NormalizeMapLon( dataXLoc + selectionDim[0] ) sliceSize = imageLen[0] * ( ( cut0 - self.map_cut ) / 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent = list( baseExtent ) extent[0:2] = [ x0, x0 + sliceCoord - 1 ] clip0 = vtk.vtkImageClip() clip0.ClipDataOn() clip0.SetInput( baseImage ) clip0.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] ) size0 = extent[1] - extent[0] + 1 self.x0 = dataLocation[0] - selectionDim[0] cut1 = self.NormalizeMapLon( self.x0 ) sliceSize = imageLen[0] * ( ( cut1 - self.map_cut )/ 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent[0:2] = [ x0 + sliceCoord, x1 ] clip1 = vtk.vtkImageClip() clip1.ClipDataOn() if vtk.VTK_MAJOR_VERSION <= 5: clip1.SetInput( baseImage ) else: clip1.SetInputData( baseImage ) clip1.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] ) size1 = extent[1] - extent[0] + 1 # print "Set Corner pos: %s, cuts: %s " % ( str(self.x0), str( (cut0, cut1) ) ) append = vtk.vtkImageAppend() append.SetAppendAxis( 0 ) append.AddInputConnection( clip1.GetOutputPort() ) append.AddInputConnection( clip0.GetOutputPort() ) bounded_dims = ( size0 + size1, vertExtent[1] - vertExtent[0] + 1 ) imageInfo.SetInputConnection( append.GetOutputPort() ) else: self.x0 = dataXLoc - selectionDim[0] cut0 = self.NormalizeMapLon( self.x0 ) sliceSize = imageLen[0] * ( ( cut0 - self.map_cut ) / 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent = list( baseExtent ) extent[0] = x0 + sliceCoord - 1 cut1 = self.NormalizeMapLon( dataXLoc + selectionDim[0] ) sliceSize = imageLen[0] * ( ( cut1 - self.map_cut ) / 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent[1] = x0 + sliceCoord clip = vtk.vtkImageClip() clip.ClipDataOn() if vtk.VTK_MAJOR_VERSION <= 5: clip.SetInput( baseImage ) else: clip.SetInputData( baseImage ) clip.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] ) bounded_dims = ( extent[1] - extent[0] + 1, vertExtent[1] - vertExtent[0] + 1 ) # print "Set Corner pos: %s, dataXLoc: %s " % ( str(self.x0), str( (dataXLoc, selectionDim[0]) ) ) clip.Update() imageInfo.SetInputConnection( clip.GetOutputPort() ) imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 ) imageInfo.SetOutputExtentStart( 0, 0, 0 ) imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] ) imageInfo.Update() result = imageInfo.GetOutput() return result, bounded_dims
def _BuildPipeline(self): """_BuildPipeline - Builds the visualization pipeline""" image = component.getUtility(ICurrentImage) # update image (VTK-6 compatible) image.Update() # image reslice object reslice = vtk.vtkImageReslice() reslice.SetInterpolationModeToCubic() reslice.ReleaseDataFlagOn() reslice.SetInputConnection(image.GetOutputPort()) if self._transform: reslice.SetTransform(self._transform) # get extents, spacings, etc in_extent = image.GetExtent() in_spacing = image.GetSpacing() in_origin = image.GetOrigin() # get stencil data stencil_data = image.GetStencilData() # Set image resample factor f = self.gui.m_sliderSurfaceQuality.GetValue() / 100.0 if f == 0.0: f = 0.001 # Set surface decimation factor decf = self.gui.m_sliderDecimationFactor.GetValue() / 100.0 # Enable/Disable stencil usage if self.gui.m_checkBoxClipping.GetValue() is True and stencil_data: if vtk.vtkVersion().GetVTKMajorVersion() > 5: reslice.SetStencilData(stencil_data) else: reslice.SetStencil(stencil_data) reslice.SetBackgroundLevel(image.GetScalarRange()[0]) ext = stencil_data.GetExtent() else: ext = in_extent if vtk.vtkVersion().GetVTKMajorVersion() > 5: reslice.SetStencilData(None) else: reslice.SetStencil(None) # expand extent slightly - account for downsampling later too fudge = int(math.ceil(1.0 / f)) ext = [ ext[0] - fudge, ext[1] + fudge, ext[2] - fudge, ext[3] + fudge, ext[4] - fudge, ext[5] + fudge ] reslice.SetOutputExtent(ext) # set default origin/spacing -- these two lines work... reslice.SetOutputSpacing(in_spacing) reslice.SetOutputOrigin(in_origin) # do we need to downsample the image? if (f < 1.0): resample = vtk.vtkImageResample() resample.SetInputConnection(reslice.GetOutputPort()) resample.ReleaseDataFlagOn() for i in range(3): resample.SetAxisMagnificationFactor(i, f) obj = resample else: obj = reslice # do we need to smooth the image? if (self.gui.m_checkBoxImageSmoothing.GetValue() == True): smooth = vtk.vtkImageGaussianSmooth() smooth.SetStandardDeviation(1.0) smooth.ReleaseDataFlagOn() smooth.SetInputConnection(obj.GetOutputPort()) obj = smooth clip = vtk.vtkImageClip() clip.SetInputConnection(obj.GetOutputPort()) # setup contour filter cf = vtk.vtkMarchingCubes() cf.SetNumberOfContours(1) val = float(self.gui.m_textCtrlImageThreshold.GetValue()) cf.SetValue(0, val) cf.SetComputeScalars(0) cf.SetComputeNormals(0) cf.SetInputConnection(clip.GetOutputPort()) # decimate surface decimate = vtk.vtkDecimatePro() decimate.SetInputConnection(cf.GetOutputPort()) decimate.PreserveTopologyOn() decimate.SetTargetReduction(decf) # To cut down on memory consumption, we use the clip object # to process the image a chunk at a time. By default we # use 20 chunks -- but if the chunks are too small, we'll adjust this # number clip.UpdateInformation() ext = clip.GetInput().GetExtent() # main processing loop with wx.BusyCursor(): event.notify(ProgressEvent("Generating surface...", 0.0)) clip.SetOutputWholeExtent(ext[0], ext[1], ext[2], ext[3], ext[4], ext[5]) decimate.Update() event.notify(ProgressEvent("Generating surface...", 1.0)) # Create the rendered Geometry if not self._app_states[self._current_image_index].GetFactory(): self._app_states[self._current_image_index].SetFactory( vtkAtamai.SurfaceObjectFactory.SurfaceObjectFactory()) self._app_states[ self._current_image_index].GetFactory().SetInputConnection( decimate.GetOutputPort()) self._app_states[ self._current_image_index].GetFactory().SetBackfaceProperty( self._app_states[ self._current_image_index].GetFactory().GetProperty()) self._app_states[ self._current_image_index].GetFactory().NormalGenerationOn() self.SetSurfaceColor() self.GetMicroView().pane3D.ConnectActorFactory( self._app_states[self._current_image_index].GetFactory()) self._app_states[self._current_image_index]._disconnected = False # Update math values self.UpdateMathValues()