def GetModelSnapshot(): lm = slicer.app.layoutManager() lm.setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutFourUpView) view = lm.threeDWidget(0).threeDView() viewNode = view.mrmlViewNode() view.resetFocalPoint() viewNode.SetBackgroundColor((0,0,0)) viewNode.SetBackgroundColor2((0,0,0)) viewNode.SetAxisLabelsVisible(0) viewNode.SetBoxVisible(0) view.lookFromViewAxis(4) view.setPitchRollYawIncrement(90) view.pitch() view.setPitchRollYawIncrement(30) view.yaw() view.pitchDirection = 1 view.pitch() view.setZoomFactor(10) view.zoomIn() #view.setZoomFactor(5) #view.zoomIn() #view.zoomIn() view.forceRender() rw=view.renderWindow() wti=vtk.vtkWindowToImageFilter() wti.SetInput(rw) slicer.app.processEvents() wti.Update() imgData3D = wti.GetOutput() return(imgData3D)
def GetModelSnapshot(): lm = slicer.app.layoutManager() lm.setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutFourUpView) view = lm.threeDWidget(0).threeDView() viewNode = view.mrmlViewNode() view.resetFocalPoint() viewNode.SetBackgroundColor((0, 0, 0)) viewNode.SetBackgroundColor2((0, 0, 0)) viewNode.SetAxisLabelsVisible(0) viewNode.SetBoxVisible(0) view.lookFromViewAxis(4) view.setPitchRollYawIncrement(90) view.pitch() view.setPitchRollYawIncrement(30) view.yaw() view.pitchDirection = 1 view.pitch() view.setZoomFactor(10) view.zoomIn() #view.setZoomFactor(5) #view.zoomIn() #view.zoomIn() view.forceRender() rw = view.renderWindow() wti = vtk.vtkWindowToImageFilter() wti.SetInput(rw) slicer.app.processEvents() wti.Update() imgData3D = wti.GetOutput() return (imgData3D)
def run(self): httpd = StoppableHttpServer(self.PORT) self.httpdProcess = Process(target=httpd.serve_forever) self.q= multiprocessing.Queue(1) websocket_process = Process(target=startwebsocket, args=(8081,self.q)) import sys oldstdin = sys.stdin; oldstdout = sys.stdout; oldstderr = sys.stderr; filein = open("/home/utsav/tmp/stdin","r") fileout = open("/home/utsav/tmp/stdout","w") fileerr = open("/home/utsav/tmp/stderr","w") sys.stdin = filein; sys.stdout = fileout; sys.stderr = fileerr; print "starting" websocket_process.start() self.httpdProcess.start() sys.stdin = oldstdin; sys.stdout = oldstdout; sys.stderr = oldstderr; ren = slicer.app.layoutManager().activeThreeDRenderer() self.w2i = vtk.vtkWindowToImageFilter() self.w2i.SetInput(ren.GetRenderWindow()) self.w2i.SetInputBufferTypeToRGBA() self.w2i.ShouldRerenderOff() self.writer = vtk.vtkJPEGWriter() self.writer.WriteToMemoryOn() viewNode = slicer.util.getNodes('vtkMRMLViewNode*').values()[0] viewNode.SetStereoType(6) ren.GetRenderWindow().SetStereoTypeToSplitViewportHorizontal() ren.GetRenderWindow().Render() ren.AddObserver('EndEvent',self.OnRender)
def generate(self, volumeRenderingNode, filePattern="/tmp/slice_%04d.png"): # underscore not dash self.cancelRequested = False # Ensure view node and widget exists and cross-references are up-to-date self.create3dView(volumeRenderingNode) self.threeDViewNode.SetAndObserveParentLayoutNodeID( volumeRenderingNode.GetID()) self.threeDWidget.setMRMLViewNode(self.threeDViewNode) # Make sure the selected volume rendering node is visible in the capture view if not volumeRenderingNode.IsDisplayableInView( self.threeDViewNode.GetID()): volumeRenderingNode.AddViewNodeID(self.threeDViewNode.GetID()) # Configure view and widget self.threeDViewNode.SetBoxVisible(0) self.threeDViewNode.SetAxisLabelsVisible(0) self.threeDViewNode.SetVolumeRenderingQuality( slicer.vtkMRMLViewNode.Normal ) # viewNode.Maximum could provide better quality but slower self.threeDViewNode.SetRenderMode(slicer.vtkMRMLViewNode.Orthographic) self.threeDViewNode.SetBackgroundColor((1, 1, 1)) self.threeDViewNode.SetBackgroundColor2((1, 1, 1)) # Turn off shading. We do not want any lighting effect (specular reflections, etc.) to be baked into the image. originalShade = volumeRenderingNode.GetVolumePropertyNode( ).GetVolumeProperty().GetShade() volumeRenderingNode.GetVolumePropertyNode().GetVolumeProperty( ).SetShade(False) self.threeDWidget.resize(self.width, self.height) self.threeDWidget.show() # Save original ROI volumeRenderingNode.SetCroppingEnabled(True) roi = volumeRenderingNode.GetROINode() roiCenter = [0] * 3 roiRadius = [0] * 3 roi.GetXYZ(roiCenter) roi.GetRadiusXYZ(roiRadius) originalRoiVisibility = roi.GetDisplayVisibility() roi.SetDisplayVisibility(False) cameraPositionOffset = 100.0 cameraNode = slicer.modules.cameras.logic().GetViewActiveCameraNode( self.threeDViewNode) cameraNode.SetFocalPoint(roiCenter) cameraNode.SetPosition( roiCenter[0], roiCenter[1], roiCenter[2] + roiRadius[2] + cameraPositionOffset) cameraNode.SetViewUp((0, 1, 0)) cameraNode.GetCamera().SetClippingRange( cameraPositionOffset / 2.0, roiRadius[2] * 2 + cameraPositionOffset * 2.0) windowSizeInPixels = self.threeDWidget.threeDView().renderWindow( ).GetSize() pixelSizeInMm = 25.4 / self.yResolutionDpi heightOfViewportInMm = windowSizeInPixels[ 1] * pixelSizeInMm / self.printScale cameraNode.SetParallelScale(heightOfViewportInMm) # cycle through the slabs slabRadius = list(roiRadius) slabRadius[2] = self.slabThickness roi.SetRadiusXYZ(slabRadius) slabCounter = 0 slabCenter = [roiCenter[0], roiCenter[1], roiCenter[2] - roiRadius[2]] slabTop = roiCenter[2] + roiRadius[2] scaledSlabSpacingMm = self.slabSpacingMm / self.printScale numberOfSlabs = int(roiRadius[2] * 2.0 / scaledSlabSpacingMm) + 1 threeDView = self.threeDWidget.threeDView() renderWindow = threeDView.renderWindow() renderer = renderWindow.GetRenderers().GetFirstRenderer() originalCameraUserTransform = cameraNode.GetCamera().GetUserTransform() originalPixelAspect = renderer.GetPixelAspect() cameraUserTransform = vtk.vtkTransform() cameraUserTransform.Scale(self.xResolutionDpi / self.yResolutionDpi, 1.0, 1.0) cameraNode.GetCamera().SetUserTransform(cameraUserTransform) if self.transparentBackground: originalAlphaBitPlanes = renderWindow.GetAlphaBitPlanes() renderWindow.SetAlphaBitPlanes(1) originalGradientBackground = renderer.GetGradientBackground() renderer.SetGradientBackground(False) logging.info("Starting render...") while slabCenter[2] <= slabTop: slicer.app.processEvents() if self.cancelRequested: break roi.SetXYZ(slabCenter) threeDView.forceRender() windowToImage = vtk.vtkWindowToImageFilter() if self.transparentBackground: windowToImage.SetInputBufferTypeToRGBA() renderWindow.Render() windowToImage.SetInput(renderWindow) # Write to file with custom DPI # (use Qt file writer to allow saving DPI values) filename = "c:/tmp/test.png" windowToImage.Update() vtkImage = windowToImage.GetOutput() qImage = qt.QImage() slicer.qMRMLUtils().vtkImageDataToQImage(vtkImage, qImage) inchesPerMeter = 1000 / 25.4 qImage.setDotsPerMeterX(self.xResolutionDpi * inchesPerMeter) qImage.setDotsPerMeterY(self.yResolutionDpi * inchesPerMeter) imagePixmap = qt.QPixmap.fromImage(qImage) filePath = filePattern % slabCounter imagePixmap.save(filePath) slabCounter += 1 slabCenter[2] = slabCenter[2] + scaledSlabSpacingMm logging.info("Slab {0}/{1} saved to {2}".format( slabCounter, numberOfSlabs, filePath)) self.threeDWidget.hide() # reset ROI roi.SetXYZ(roiCenter) roi.SetRadiusXYZ(roiRadius) roi.SetDisplayVisibility(originalRoiVisibility) cameraNode.GetCamera().SetUserTransform(originalCameraUserTransform) if self.transparentBackground: renderWindow.SetAlphaBitPlanes(originalAlphaBitPlanes) renderer.SetGradientBackground(originalGradientBackground) volumeRenderingNode.GetVolumePropertyNode().GetVolumeProperty( ).SetShade(originalShade) # for debugging convenience slicer.modules.BitmapGeneratorWidget.threeDWidget = self.threeDWidget slicer.modules.BitmapGeneratorWidget.threeDViewNode = self.threeDViewNode slicer.modules.BitmapGeneratorWidget.volumeRenderingNode = volumeRenderingNode if self.cancelRequested: raise ValueError('User requested cancel.')
def threeD(self,cmd): """return a png for a threeD view Args: view={nodeid} (currently ignored) """ pngMethod = 'PIL' if not hasImage: pngMethod = 'VTK' import numpy import vtk.util.numpy_support import slicer try: import cStringIO as StringIO except ImportError: import StringIO p = urlparse.urlparse(cmd) q = urlparse.parse_qs(p.query) try: view = q['view'][0].strip().lower() except KeyError: view = '1' try: size = int(q['size'][0].strip()) except (KeyError, ValueError): size = None try: mode = str(q['mode'][0].strip()) except (KeyError, ValueError): mode = None try: roll = float(q['roll'][0].strip()) except (KeyError, ValueError): roll = None try: panX = float(q['panX'][0].strip()) except (KeyError, ValueError): panX = None try: panY = float(q['panY'][0].strip()) except (KeyError, ValueError): panY = None try: orbitX = float(q['orbitX'][0].strip()) except (KeyError, ValueError): orbitX = None try: orbitY = float(q['orbitY'][0].strip()) except (KeyError, ValueError): orbitY = None layoutManager = slicer.app.layoutManager() view = layoutManager.threeDWidget(0).threeDView() view.renderEnabled = False if mode: cameraNode = slicer.util.getNode('*Camera*') camera = cameraNode.GetCamera() #if mode == 'start' or not self.interactionState.has_key('camera'): #startCamera = vtk.vtkCamera() #startCamera.DeepCopy(camera) #self.interactionState['camera'] = startCamera #startCamera = self.interactionState['camera'] cameraNode.DisableModifiedEventOn() camera.DeepCopy(startCamera) if roll: camera.Roll(roll*100) position = numpy.array(startCamera.GetPosition()) focalPoint = numpy.array(startCamera.GetFocalPoint()) viewUp = numpy.array(startCamera.GetViewUp()) viewPlaneNormal = numpy.array(startCamera.GetViewPlaneNormal()) viewAngle = startCamera.GetViewAngle() viewRight = numpy.cross(viewUp,viewPlaneNormal) viewDistance = numpy.linalg.norm(focalPoint - position) self.logMessage("position", position) self.logMessage("focalPoint", focalPoint) self.logMessage("viewUp", viewUp) self.logMessage("viewPlaneNormal", viewPlaneNormal) self.logMessage("viewAngle", viewAngle) self.logMessage("viewRight", viewRight) self.logMessage("viewDistance", viewDistance) if panX and panY: offset = viewDistance * -panX * viewRight + viewDistance * viewUp * panY newPosition = position + offset newFocalPoint = focalPoint + offset camera.SetPosition(newPosition) camera.SetFocalPoint(newFocalPoint) if orbitX and orbitY: offset = viewDistance * -orbitX * viewRight + viewDistance * viewUp * orbitY newPosition = position + offset newFPToEye = newPosition - focalPoint newPosition = focalPoint + viewDistance * newFPToEye / numpy.linalg.norm(newFPToEye) camera.SetPosition(newPosition) cameraNode.DisableModifiedEventOff() cameraNode.InvokePendingModifiedEvent() view.renderWindow().Render() view.renderEnabled = True w2i = vtk.vtkWindowToImageFilter() w2i.SetInput(view.renderWindow()) w2i.SetReadFrontBuffer(0) w2i.Update() imageData = w2i.GetOutput() pngData = self.vtkImageDataToPNG(imageData,method=pngMethod) self.logMessage('threeD returning an image of %d length' % len(pngData)) return pngData
def modelHandler(imageNode, labelNode, Zind): sliceZImageNode = extractMaxZSlice(imageNode, Zind) sliceZLabelNode = extractMaxZSlice(labelNode, Zind) volumesLogic = slicer.vtkSlicerVolumesLogic() volumesLogic.SetVolumeAsLabelMap(sliceZLabelNode, True) volumesLogic.SetVolumeAsLabelMap(labelNode, True) sliceZLabelNodeDisplay = sliceZLabelNode.GetDisplayNode() sliceZLabelNodeDisplay.SetAndObserveColorNodeID('vtkMRMLColorTableNodeFileGenericColors.txt') sliceZLabelNode.SetAndObserveDisplayNodeID(sliceZLabelNodeDisplay.GetID()) labelNodeDisplay = labelNode.GetDisplayNode() labelNodeDisplay.SetAndObserveColorNodeID('vtkMRMLColorTableNodeFileGenericColors.txt') labelNode.SetAndObserveDisplayNodeID(labelNodeDisplay.GetID()) ## appLogic = slicer.app.applicationLogic() selectionNode = appLogic.GetSelectionNode() selectionNode.SetReferenceActiveVolumeID(sliceZImageNode.GetID()) selectionNode.SetReferenceActiveLabelVolumeID(sliceZLabelNode.GetID()) appLogic.PropagateVolumeSelection() ## lm = slicer.app.layoutManager() lm.setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutFourUpView) redWidget = lm.sliceWidget('Red') redLogic = redWidget.sliceLogic() redView = redWidget.sliceView() #redLogic.SetBackgroundWindowLevel(*windowLevel) sln = slicer.util.getNode('vtkMRMLSliceNodeRed') dims = list(sliceZImageNode.GetImageData().GetDimensions()) # dims[0] is x, dims[1] is y, dims [2] is Z redWidget.setFixedSize(720,660) slncw = redWidget.sliceController() slncw.showLabelOutline(1) slncw.fitSliceToBackground() #sln.SetFieldOfView(dims[0],dims[1],1) #sln.SetDimensions(dims[0],dims[1],1) sliceannotations = slicer.modules.DataProbeInstance.infoWidget.sliceAnnoations if sliceannotations.sliceViewAnnotationsCheckBox.checkState() == 2: sliceannotations.sliceViewAnnotationsCheckBox.click() slicer.app.processEvents() wti=vtk.vtkWindowToImageFilter() wti.SetInput(redView.renderWindow()) wti.Update() imgDataRedSlice = wti.GetOutput() modelMakerCLI(labelNode) imgData3D = GetModelSnapshot() append = vtk.vtkImageAppend() append.SetAppendAxis(0) append.AddInputData(imgDataRedSlice) append.AddInputData(imgData3D) append.Update() finalImage = append.GetOutput() return finalImage
def generate(self, volumeRenderingNode, filePattern="/tmp/slice_%04d.png"): # underscore not dash """ """ lm = slicer.app.layoutManager() # switch on the type to get the requested window # just the 3D window mainThreeDWidget = lm.threeDWidget(0).threeDView() viewNode = mainThreeDWidget.mrmlViewNode() # create the dummy threeD widget threeDWidget = slicer.qMRMLThreeDWidget() threeDWidget.resize(self.width, self.height) threeDWidget.setObjectName("ThreeDWidget%s" % viewNode.GetLayoutLabel()) threeDWidget.setMRMLScene(slicer.mrmlScene) threeDWidget.setMRMLViewNode(viewNode) self.threeDWidget = threeDWidget threeDWidget.show() # configure the view cacheViewNode = slicer.vtkMRMLViewNode() cacheViewNode.Copy(viewNode) viewNode.SetBoxVisible(0) viewNode.SetAxisLabelsVisible(0) viewNode.SetBackgroundColor((1, 1, 1)) viewNode.SetBackgroundColor2((1, 1, 1)) roi = volumeRenderingNode.GetROINode() roiCenter = [ 0, ] * 3 roiRadius = [ 0, ] * 3 roi.GetXYZ(roiCenter) roi.GetRadiusXYZ(roiRadius) roi.SetDisplayVisibility(0) camera = vtk.vtkCamera() camera.SetFocalPoint(roiCenter) camera.SetPosition(roiCenter[0], roiCenter[1], roiCenter[2] + roiRadius[2]) camera.SetViewUp((0, 1, 0)) mrmlCamera = slicer.util.getNode('Default Scene Camera') cacheCamera = vtk.vtkCamera() cacheCamera.DeepCopy(mrmlCamera.GetCamera()) mrmlCamera.GetCamera().DeepCopy(camera) viewNode.SetRenderMode(slicer.vtkMRMLViewNode.Orthographic) # cycle through the slabs slabRadius = list(roiRadius) slabRadius[2] = self.slabThickness roi.SetRadiusXYZ(slabRadius) slabCounter = 0 slabCenter = [roiCenter[0], roiCenter[1], roiCenter[2] - roiRadius[2]] slabTop = roiCenter[2] + roiRadius[2] threeDView = threeDWidget.threeDView() renderWindow = threeDView.renderWindow() self.delayDisplay("Starting render...", 300) while slabCenter[2] <= slabTop: roi.SetXYZ(slabCenter) threeDView.forceRender() windowToImage = vtk.vtkWindowToImageFilter() windowToImage.SetInput(renderWindow) writer = vtk.vtkPNGWriter() writer.SetInputConnection(windowToImage.GetOutputPort()) filePath = filePattern % slabCounter windowToImage.Update() writer.SetFileName(filePath) writer.Write() slabCounter += 1 slabCenter[2] = slabCenter[2] + self.slabSpacing # reset things viewNode.Copy(cacheViewNode) mrmlCamera.GetCamera().DeepCopy(cacheCamera) roi.SetXYZ(roiCenter) roi.SetRadiusXYZ(roiRadius) roi.SetDisplayVisibility(1)
def test_ShadedModels1(self): """ Ideally you should have several levels of tests. At the lowest level tests should exercise the functionality of the logic with different inputs (both valid and invalid). At higher levels your tests should emulate the way the user would interact with your code and confirm that it still works the way you intended. One of the most important features of the tests is that it should alert other developers when their changes will have an impact on the behavior of your module. For example, if a developer removes a feature that you depend on, your test should break so they know that the feature is needed. """ self.delayDisplay("Starting the test") import SampleData sampleDataLogic = SampleData.SampleDataLogic() print("Getting MR Head Volume") mrHeadVolume = sampleDataLogic.downloadMRHead() resize = vtk.vtkImageResize() resize.SetInputDataObject(mrHeadVolume.GetImageData()) resize.SetOutputDimensions(256,256,128) resize.Update() tdw = slicer.qMRMLThreeDWidget() tdw.setMRMLScene(slicer.mrmlScene) tdw.setMRMLViewNode(slicer.util.getNode("*ViewNode*")) tdw.show() from vtkSlicerShadedActorModuleLogicPython import * shadedActor=vtkOpenGLShadedActor() tdv = tdw.threeDView() rw = tdv.renderWindow() rens = rw.GetRenderers() ren = rens.GetItemAsObject(0) ren.AddActor(shadedActor) mapper = vtk.vtkPolyDataMapper() shadedActor.SetMapper(mapper) shadedActor.SetVertexShaderSource(""" #version 120 attribute vec3 vertexAttribute; attribute vec2 textureCoordinateAttribute; varying vec4 interpolatedColor; varying vec3 interpolatedTextureCoordinate; void main() { interpolatedColor = vec4(0.5) + vec4(vertexAttribute, 1.); interpolatedTextureCoordinate = vec3(textureCoordinateAttribute, .5); gl_Position = vec4(vertexAttribute, 1.); } """) shadedActor.SetFragmentShaderSource(""" #version 120 varying vec4 interpolatedColor; varying vec3 interpolatedTextureCoordinate; uniform sampler3D volumeSampler; void main() { gl_FragColor = vec4 ( 1.0, 0.0, 0.0, 1.0 ); gl_FragColor = interpolatedColor; vec4 volumeSample = texture3D(volumeSampler, interpolatedTextureCoordinate); volumeSample *= 100; gl_FragColor = mix( volumeSample, interpolatedColor, 0.5); vec4 integratedRay = vec4(0.); for (int i = 0; i < 256; i++) { vec3 samplePoint = vec3(interpolatedTextureCoordinate.st, i/256.); vec4 volumeSample = texture3D(volumeSampler, samplePoint); integratedRay += volumeSample; } gl_FragColor = integratedRay; } """) shadedActor.SetTextureImageData(resize.GetOutputDataObject(0)) #shadedActor.SetTextureImageData(mrHeadVolume.GetImageData()) sphereSource = vtk.vtkSphereSource() mapper.SetInputConnection(sphereSource.GetOutputPort()) actor = vtk.vtkActor() actor.SetScale(20,20,20) actor.SetMapper(mapper) ren.AddActor(actor) rw.Render() wti = vtk.vtkWindowToImageFilter() wti.SetInput(rw) iv = vtk.vtkImageViewer() iv.SetColorLevel(128) iv.SetColorWindow(256) iv.SetInputConnection(wti.GetOutputPort()) iv.Render() extensionManager = vtk.vtkOpenGLExtensionManager() extensionManager.SetRenderWindow(rw) extensionManager.Update() print(extensionManager) print(extensionManager.GetDriverGLVendor()) print(extensionManager.GetDriverGLVersion()) print(extensionManager.GetDriverGLRenderer()) slicer.modules.ShadedModelsWidget.tdw = tdw slicer.modules.ShadedModelsWidget.iv = iv
def takeScreenshot(self,name,type=-1): # show the message even if not taking a screen shot filePath = '/u/kanderle/Transfer/Movie/'+name+'.png' if self.enableScreenshots == 0: return lm = slicer.app.layoutManager() description = '4D' # switch on the type to get the requested window widget = 0 if type == -1: # full window widget = slicer.util.mainWindow() elif type == slicer.qMRMLScreenShotDialog().FullLayout: # full layout widget = lm.viewport() elif type == slicer.qMRMLScreenShotDialog().ThreeD: # just the 3D window widget = lm.threeDWidget(0).threeDView() elif type == slicer.qMRMLScreenShotDialog().Red: # red slice window widget = lm.sliceWidget("Red") elif type == slicer.qMRMLScreenShotDialog().Yellow: # yellow slice window widget = lm.sliceWidget("Yellow") elif type == slicer.qMRMLScreenShotDialog().Green: # green slice window widget = lm.sliceWidget("Green") # grab and convert to vtk image data if type == slicer.qMRMLScreenShotDialog().ThreeD: degrees = 71 n = 0 # heartBeat = 0 heartDisplayNode = None color = [0.56,0,0] widget = lm.threeDWidget(0).threeDView() for i in range(0,degrees): if i < 10: number = '0' + str(i) else: number = str(i) filePath = '/u/kanderle/Transfer/Movie/'+name+'_'+number+'.png' #if i%heartBeat == 0: #if heartDisplayNode: #heartDisplayNode.SetVisibility(0) #n += 1 #if n>10: #n = 1 #print "Changing state to: " + str(n) #heartNode = slicer.util.getNode('Heart_' + str(n)) #if not heartNode: #print "No Heart Node" #n = n+1 #continue #heartDisplayNode = heartNode.GetDisplayNode() #heartDisplayNode.SetColor(color) #heartDisplayNode.SetVisibility(1) #heartDisplayNode.SetOpacity(0.8) rw = widget.renderWindow() wti = vtk.vtkWindowToImageFilter() wti.SetInput(rw) wti.Update() writer = vtk.vtkPNGWriter() writer.SetFileName(filePath) writer.SetInputConnection(wti.GetOutputPort()) writer.Write() widget.yaw() widget.forceRender() else: qpixMap = qt.QPixmap().grabWidget(widget) qimage = qpixMap.toImage() imageData = vtk.vtkImageData() slicer.qMRMLUtils().qImageToVtkImageData(qimage,imageData) annotationLogic = slicer.modules.annotations.logic() annotationLogic.CreateSnapShot(name, description, type, self.screenshotScaleFactor, imageData)
def modelHandler(ImageFilePath, imageNode, labelNode, imgOutputDir, IDcurrPatient, Zind): """ imageBuffer = vtk.vtkImageData() label = growCut(imageNode.GetImageData(),labelNode.GetImageData(),imageBuffer) q = labelNode.GetImageData() q.DeepCopy(label) if labelNode.GetImageDataConnection(): labelNode.GetImageDataConnection().GetProducer().Update() if labelNode.GetImageData().GetPointData().GetScalars() != None: labelNode.GetImageData().GetPointData().GetScalars().Modified() labelNode.GetImageData().Modified() labelNode.Modified() pdb.set_trace() """ imageSeriesDescription = os.path.basename(ImageFilePath).replace( '.nrrd', '') imagePatientID = os.path.basename( os.path.dirname(os.path.dirname(os.path.dirname((ImageFilePath))))) imageStudyDate = os.path.basename( os.path.dirname(os.path.dirname((ImageFilePath)))) imagePatientID_StudyDate = imagePatientID + '_' + imageStudyDate inputImage = su.PullFromSlicer(imageNode.GetName()) inputLabel = su.PullFromSlicer(labelNode.GetName()) pixelID = inputImage.GetPixelIDValue() FlipYAxis = sitk.FlipImageFilter() FlipYAxis.SetFlipAxes([False, True, False]) sizeZ = list(inputImage.GetSize()) sizeZ[2] = 0 indexZ = [0, 0, Zind] ExtractorZ = sitk.ExtractImageFilter() ExtractorZ.SetSize(sizeZ) ExtractorZ.SetIndex(indexZ) sliceZImage = ExtractorZ.Execute(inputImage) sliceZLabel = ExtractorZ.Execute(inputLabel) imageName = 'Axial_Slice_Image' + IDcurrPatient labelName = 'Axial_Slice_Label' + IDcurrPatient su.PushToSlicer(sliceZImage, imageName) su.PushToSlicer(sliceZLabel, labelName) sliceZImageNode = slicer.util.getNode(imageName) sliceZLabelNode = slicer.util.getNode(labelName) volumesLogic = slicer.vtkSlicerVolumesLogic() volumesLogic.SetVolumeAsLabelMap(sliceZLabelNode, True) volumesLogic.SetVolumeAsLabelMap(labelNode, True) #sliceZLabelNode = binarizeLabelMapToValue(sliceZLabelNode, labelValue=296) #labelNode = binarizeLabelMapToValue(labelNode, labelValue=296) sliceZLabelNodeDisplay = sliceZLabelNode.GetDisplayNode() sliceZLabelNodeDisplay.SetAndObserveColorNodeID( 'vtkMRMLColorTableNodeFileGenericColors.txt') sliceZLabelNode.SetAndObserveDisplayNodeID(sliceZLabelNodeDisplay.GetID()) labelNodeDisplay = labelNode.GetDisplayNode() labelNodeDisplay.SetAndObserveColorNodeID( 'vtkMRMLColorTableNodeFileGenericColors.txt') labelNode.SetAndObserveDisplayNodeID(labelNodeDisplay.GetID()) ## appLogic = slicer.app.applicationLogic() selectionNode = appLogic.GetSelectionNode() selectionNode.SetReferenceActiveVolumeID(sliceZImageNode.GetID()) selectionNode.SetReferenceActiveLabelVolumeID(sliceZLabelNode.GetID()) appLogic.PropagateVolumeSelection() ## lm = slicer.app.layoutManager() lm.setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutFourUpView) redWidget = lm.sliceWidget('Red') redLogic = redWidget.sliceLogic() redView = redWidget.sliceView() #redLogic.SetBackgroundWindowLevel(*windowLevel) sln = slicer.util.getNode('vtkMRMLSliceNodeRed') dims = list(sliceZImageNode.GetImageData().GetDimensions()) # dims[0] is x, dims[1] is y, dims [2] is Z redWidget.setFixedSize(720, 660) slncw = redWidget.sliceController() slncw.showLabelOutline(1) slncw.fitSliceToBackground() #sln.SetFieldOfView(dims[0],dims[1],1) #sln.SetDimensions(dims[0],dims[1],1) sliceannotations = slicer.modules.DataProbeInstance.infoWidget.sliceAnnoations if sliceannotations.sliceViewAnnotationsCheckBox.checkState() == 2: sliceannotations.sliceViewAnnotationsCheckBox.click() slicer.app.processEvents() wti = vtk.vtkWindowToImageFilter() wti.SetInput(redView.renderWindow()) wti.Update() imgDataRedSlice = wti.GetOutput() modelMakerCLI(labelNode) imgData3D = GetModelSnapshot() append = vtk.vtkImageAppend() append.SetAppendAxis(0) append.AddInputData(imgDataRedSlice) append.AddInputData(imgData3D) append.Update() finalImage = append.GetOutput() #finalImagePath = str(os.path.join(imgOutputDir, IDcurrPatient + '_axial_sliceZ.png')) finalImagePath = str( os.path.join( imgOutputDir, imagePatientID_StudyDate + '_' + imageSeriesDescription + '.png')) writer = vtk.vtkPNGWriter() writer.SetFileName(finalImagePath) writer.SetInputData(finalImage) writer.Write()
def threeD(self, cmd): """return a png for a threeD view Args: view={nodeid} (currently ignored) """ pngMethod = 'PIL' if not hasImage: pngMethod = 'VTK' import numpy import vtk.util.numpy_support import slicer try: import cStringIO as StringIO except ImportError: import StringIO p = urlparse.urlparse(cmd) q = urlparse.parse_qs(p.query) try: view = q['view'][0].strip().lower() except KeyError: view = '1' try: size = int(q['size'][0].strip()) except (KeyError, ValueError): size = None try: mode = str(q['mode'][0].strip()) except (KeyError, ValueError): mode = None try: roll = float(q['roll'][0].strip()) except (KeyError, ValueError): roll = None try: panX = float(q['panX'][0].strip()) except (KeyError, ValueError): panX = None try: panY = float(q['panY'][0].strip()) except (KeyError, ValueError): panY = None try: orbitX = float(q['orbitX'][0].strip()) except (KeyError, ValueError): orbitX = None try: orbitY = float(q['orbitY'][0].strip()) except (KeyError, ValueError): orbitY = None layoutManager = slicer.app.layoutManager() view = layoutManager.threeDWidget(0).threeDView() view.renderEnabled = False if mode: cameraNode = slicer.util.getNode('*Camera*') camera = cameraNode.GetCamera() #if mode == 'start' or not self.interactionState.has_key('camera'): #startCamera = vtk.vtkCamera() #startCamera.DeepCopy(camera) #self.interactionState['camera'] = startCamera #startCamera = self.interactionState['camera'] cameraNode.DisableModifiedEventOn() camera.DeepCopy(startCamera) if roll: camera.Roll(roll * 100) position = numpy.array(startCamera.GetPosition()) focalPoint = numpy.array(startCamera.GetFocalPoint()) viewUp = numpy.array(startCamera.GetViewUp()) viewPlaneNormal = numpy.array(startCamera.GetViewPlaneNormal()) viewAngle = startCamera.GetViewAngle() viewRight = numpy.cross(viewUp, viewPlaneNormal) viewDistance = numpy.linalg.norm(focalPoint - position) self.logMessage("position", position) self.logMessage("focalPoint", focalPoint) self.logMessage("viewUp", viewUp) self.logMessage("viewPlaneNormal", viewPlaneNormal) self.logMessage("viewAngle", viewAngle) self.logMessage("viewRight", viewRight) self.logMessage("viewDistance", viewDistance) if panX and panY: offset = viewDistance * -panX * viewRight + viewDistance * viewUp * panY newPosition = position + offset newFocalPoint = focalPoint + offset camera.SetPosition(newPosition) camera.SetFocalPoint(newFocalPoint) if orbitX and orbitY: offset = viewDistance * -orbitX * viewRight + viewDistance * viewUp * orbitY newPosition = position + offset newFPToEye = newPosition - focalPoint newPosition = focalPoint + viewDistance * newFPToEye / numpy.linalg.norm( newFPToEye) camera.SetPosition(newPosition) cameraNode.DisableModifiedEventOff() cameraNode.InvokePendingModifiedEvent() view.renderWindow().Render() view.renderEnabled = True w2i = vtk.vtkWindowToImageFilter() w2i.SetInput(view.renderWindow()) w2i.SetReadFrontBuffer(0) w2i.Update() imageData = w2i.GetOutput() pngData = self.vtkImageDataToPNG(imageData, method=pngMethod) self.logMessage('threeD returning an image of %d length' % len(pngData)) return pngData
def modelHandler(imageNode, labelNode, Zind): sliceZImageNode = extractMaxZSlice(imageNode, Zind) sliceZLabelNode = extractMaxZSlice(labelNode, Zind) volumesLogic = slicer.vtkSlicerVolumesLogic() volumesLogic.SetVolumeAsLabelMap(sliceZLabelNode, True) volumesLogic.SetVolumeAsLabelMap(labelNode, True) sliceZLabelNodeDisplay = sliceZLabelNode.GetDisplayNode() sliceZLabelNodeDisplay.SetAndObserveColorNodeID( 'vtkMRMLColorTableNodeFileGenericColors.txt') sliceZLabelNode.SetAndObserveDisplayNodeID(sliceZLabelNodeDisplay.GetID()) labelNodeDisplay = labelNode.GetDisplayNode() labelNodeDisplay.SetAndObserveColorNodeID( 'vtkMRMLColorTableNodeFileGenericColors.txt') labelNode.SetAndObserveDisplayNodeID(labelNodeDisplay.GetID()) ## appLogic = slicer.app.applicationLogic() selectionNode = appLogic.GetSelectionNode() selectionNode.SetReferenceActiveVolumeID(sliceZImageNode.GetID()) selectionNode.SetReferenceActiveLabelVolumeID(sliceZLabelNode.GetID()) appLogic.PropagateVolumeSelection() ## lm = slicer.app.layoutManager() lm.setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutFourUpView) redWidget = lm.sliceWidget('Red') redLogic = redWidget.sliceLogic() redView = redWidget.sliceView() #redLogic.SetBackgroundWindowLevel(*windowLevel) sln = slicer.util.getNode('vtkMRMLSliceNodeRed') dims = list(sliceZImageNode.GetImageData().GetDimensions()) # dims[0] is x, dims[1] is y, dims [2] is Z redWidget.setFixedSize(720, 660) slncw = redWidget.sliceController() slncw.showLabelOutline(1) slncw.fitSliceToBackground() #sln.SetFieldOfView(dims[0],dims[1],1) #sln.SetDimensions(dims[0],dims[1],1) sliceannotations = slicer.modules.DataProbeInstance.infoWidget.sliceAnnoations if sliceannotations.sliceViewAnnotationsCheckBox.checkState() == 2: sliceannotations.sliceViewAnnotationsCheckBox.click() slicer.app.processEvents() wti = vtk.vtkWindowToImageFilter() wti.SetInput(redView.renderWindow()) wti.Update() imgDataRedSlice = wti.GetOutput() modelMakerCLI(labelNode) imgData3D = GetModelSnapshot() append = vtk.vtkImageAppend() append.SetAppendAxis(0) append.AddInputData(imgDataRedSlice) append.AddInputData(imgData3D) append.Update() finalImage = append.GetOutput() return finalImage
def modelHandler(ImageFilePath, imageNode, labelNode, imgOutputDir, IDcurrPatient, Zind): """ imageBuffer = vtk.vtkImageData() label = growCut(imageNode.GetImageData(),labelNode.GetImageData(),imageBuffer) q = labelNode.GetImageData() q.DeepCopy(label) if labelNode.GetImageDataConnection(): labelNode.GetImageDataConnection().GetProducer().Update() if labelNode.GetImageData().GetPointData().GetScalars() != None: labelNode.GetImageData().GetPointData().GetScalars().Modified() labelNode.GetImageData().Modified() labelNode.Modified() pdb.set_trace() """ imageSeriesDescription = os.path.basename(ImageFilePath).replace('.nrrd','') imagePatientID = os.path.basename(os.path.dirname(os.path.dirname(os.path.dirname((ImageFilePath))))) imageStudyDate = os.path.basename(os.path.dirname(os.path.dirname((ImageFilePath)))) imagePatientID_StudyDate = imagePatientID + '_' + imageStudyDate inputImage = su.PullFromSlicer(imageNode.GetName()) inputLabel = su.PullFromSlicer(labelNode.GetName()) pixelID = inputImage.GetPixelIDValue() FlipYAxis = sitk.FlipImageFilter() FlipYAxis.SetFlipAxes([False, True, False]) sizeZ = list(inputImage.GetSize()) sizeZ[2] = 0 indexZ = [0, 0, Zind] ExtractorZ = sitk.ExtractImageFilter() ExtractorZ.SetSize(sizeZ) ExtractorZ.SetIndex(indexZ) sliceZImage = ExtractorZ.Execute(inputImage) sliceZLabel = ExtractorZ.Execute(inputLabel) imageName = 'Axial_Slice_Image' + IDcurrPatient labelName = 'Axial_Slice_Label' + IDcurrPatient su.PushToSlicer(sliceZImage, imageName) su.PushToSlicer(sliceZLabel, labelName) sliceZImageNode = slicer.util.getNode(imageName) sliceZLabelNode = slicer.util.getNode(labelName) volumesLogic = slicer.vtkSlicerVolumesLogic() volumesLogic.SetVolumeAsLabelMap(sliceZLabelNode, True) volumesLogic.SetVolumeAsLabelMap(labelNode, True) #sliceZLabelNode = binarizeLabelMapToValue(sliceZLabelNode, labelValue=296) #labelNode = binarizeLabelMapToValue(labelNode, labelValue=296) sliceZLabelNodeDisplay = sliceZLabelNode.GetDisplayNode() sliceZLabelNodeDisplay.SetAndObserveColorNodeID('vtkMRMLColorTableNodeFileGenericColors.txt') sliceZLabelNode.SetAndObserveDisplayNodeID(sliceZLabelNodeDisplay.GetID()) labelNodeDisplay = labelNode.GetDisplayNode() labelNodeDisplay.SetAndObserveColorNodeID('vtkMRMLColorTableNodeFileGenericColors.txt') labelNode.SetAndObserveDisplayNodeID(labelNodeDisplay.GetID()) ## appLogic = slicer.app.applicationLogic() selectionNode = appLogic.GetSelectionNode() selectionNode.SetReferenceActiveVolumeID(sliceZImageNode.GetID()) selectionNode.SetReferenceActiveLabelVolumeID(sliceZLabelNode.GetID()) appLogic.PropagateVolumeSelection() ## lm = slicer.app.layoutManager() lm.setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutFourUpView) redWidget = lm.sliceWidget('Red') redLogic = redWidget.sliceLogic() redView = redWidget.sliceView() #redLogic.SetBackgroundWindowLevel(*windowLevel) sln = slicer.util.getNode('vtkMRMLSliceNodeRed') dims = list(sliceZImageNode.GetImageData().GetDimensions()) # dims[0] is x, dims[1] is y, dims [2] is Z redWidget.setFixedSize(720,660) slncw = redWidget.sliceController() slncw.showLabelOutline(1) slncw.fitSliceToBackground() #sln.SetFieldOfView(dims[0],dims[1],1) #sln.SetDimensions(dims[0],dims[1],1) sliceannotations = slicer.modules.DataProbeInstance.infoWidget.sliceAnnoations if sliceannotations.sliceViewAnnotationsCheckBox.checkState() == 2: sliceannotations.sliceViewAnnotationsCheckBox.click() slicer.app.processEvents() wti=vtk.vtkWindowToImageFilter() wti.SetInput(redView.renderWindow()) wti.Update() imgDataRedSlice = wti.GetOutput() modelMakerCLI(labelNode) imgData3D = GetModelSnapshot() append = vtk.vtkImageAppend() append.SetAppendAxis(0) append.AddInputData(imgDataRedSlice) append.AddInputData(imgData3D) append.Update() finalImage = append.GetOutput() #finalImagePath = str(os.path.join(imgOutputDir, IDcurrPatient + '_axial_sliceZ.png')) finalImagePath = str(os.path.join(imgOutputDir, imagePatientID_StudyDate + '_' + imageSeriesDescription +'.png')) writer=vtk.vtkPNGWriter() writer.SetFileName(finalImagePath) writer.SetInputData(finalImage) writer.Write()
def test_ShadedModels1(self): """ Ideally you should have several levels of tests. At the lowest level tests should exercise the functionality of the logic with different inputs (both valid and invalid). At higher levels your tests should emulate the way the user would interact with your code and confirm that it still works the way you intended. One of the most important features of the tests is that it should alert other developers when their changes will have an impact on the behavior of your module. For example, if a developer removes a feature that you depend on, your test should break so they know that the feature is needed. """ self.delayDisplay("Starting the test") import SampleData sampleDataLogic = SampleData.SampleDataLogic() print("Getting MR Head Volume") mrHeadVolume = sampleDataLogic.downloadMRHead() resize = vtk.vtkImageResize() resize.SetInputDataObject(mrHeadVolume.GetImageData()) resize.SetOutputDimensions(256, 256, 128) resize.Update() tdw = slicer.qMRMLThreeDWidget() tdw.setMRMLScene(slicer.mrmlScene) tdw.setMRMLViewNode(slicer.util.getNode("*ViewNode*")) tdw.show() from vtkSlicerShadedActorModuleLogicPython import * shadedActor = vtkOpenGLShadedActor() tdv = tdw.threeDView() rw = tdv.renderWindow() rens = rw.GetRenderers() ren = rens.GetItemAsObject(0) ren.AddActor(shadedActor) mapper = vtk.vtkPolyDataMapper() shadedActor.SetMapper(mapper) shadedActor.SetVertexShaderSource(""" #version 120 attribute vec3 vertexAttribute; attribute vec2 textureCoordinateAttribute; varying vec4 interpolatedColor; varying vec3 interpolatedTextureCoordinate; void main() { interpolatedColor = vec4(0.5) + vec4(vertexAttribute, 1.); interpolatedTextureCoordinate = vec3(textureCoordinateAttribute, .5); gl_Position = vec4(vertexAttribute, 1.); } """) shadedActor.SetFragmentShaderSource(""" #version 120 varying vec4 interpolatedColor; varying vec3 interpolatedTextureCoordinate; uniform sampler3D volumeSampler; void main() { gl_FragColor = vec4 ( 1.0, 0.0, 0.0, 1.0 ); gl_FragColor = interpolatedColor; vec4 volumeSample = texture3D(volumeSampler, interpolatedTextureCoordinate); volumeSample *= 100; gl_FragColor = mix( volumeSample, interpolatedColor, 0.5); vec4 integratedRay = vec4(0.); for (int i = 0; i < 256; i++) { vec3 samplePoint = vec3(interpolatedTextureCoordinate.st, i/256.); vec4 volumeSample = texture3D(volumeSampler, samplePoint); integratedRay += volumeSample; } gl_FragColor = integratedRay; } """) shadedActor.SetTextureImageData(resize.GetOutputDataObject(0)) #shadedActor.SetTextureImageData(mrHeadVolume.GetImageData()) sphereSource = vtk.vtkSphereSource() mapper.SetInputConnection(sphereSource.GetOutputPort()) actor = vtk.vtkActor() actor.SetScale(20, 20, 20) actor.SetMapper(mapper) ren.AddActor(actor) rw.Render() wti = vtk.vtkWindowToImageFilter() wti.SetInput(rw) iv = vtk.vtkImageViewer() iv.SetColorLevel(128) iv.SetColorWindow(256) iv.SetInputConnection(wti.GetOutputPort()) iv.Render() extensionManager = vtk.vtkOpenGLExtensionManager() extensionManager.SetRenderWindow(rw) extensionManager.Update() print(extensionManager) print(extensionManager.GetDriverGLVendor()) print(extensionManager.GetDriverGLVersion()) print(extensionManager.GetDriverGLRenderer()) slicer.modules.ShadedModelsWidget.tdw = tdw slicer.modules.ShadedModelsWidget.iv = iv