def vtkImageDataToPNG(self,imageData,method='VTK'): """Return a buffer of png data using the data from the vtkImageData. """ if method == 'PIL': if imageData: imageData.Update() imageScalars = imageData.GetPointData().GetScalars() imageArray = vtk.util.numpy_support.vtk_to_numpy(imageScalars) d = imageData.GetDimensions() im = Image.fromarray( numpy.flipud( imageArray.reshape([d[1],d[0],4]) ) ) else: # no data available, make a small black opaque image a = numpy.zeros(100*100*4, dtype='uint8').reshape([100,100,4]) a[:,:,3] = 255 im = Image.fromarray( a ) if size: im.thumbnail((size,size), Image.ANTIALIAS) pngStringIO = StringIO.StringIO() im.save(pngStringIO, format="PNG") pngData = pngStringIO.getvalue() elif method == 'VTK': writer = vtk.vtkPNGWriter() writer.SetWriteToMemory(True) writer.SetInput(imageData) writer.Write() result = writer.GetResult() pngArray = vtk.util.numpy_support.vtk_to_numpy(result) pngStringIO = StringIO.StringIO() pngStringIO.write(pngArray) pngData = pngStringIO.getvalue() return pngData
def ImageModelSnapshot(imageNode, labelNode, outputImagePath, progress_filename): castScalarToInt(imageNode) castScalarToInt(labelNode) # center label to origin of image, if needed #labelNode.SetOrigin(imageNode.GetOrigin()) try: minBounds, maxBounds = getCropBoundaries(labelNode) zoomImageNode = cropToZoom(imageNode, minBounds, maxBounds, label=False) zoomLabelNode = cropToZoom(labelNode, minBounds, maxBounds, label=True) sitkZoomLabelNode = su.PullFromSlicer(zoomLabelNode.GetName()) zoomLabelNodeArray = sitk.GetArrayFromImage(sitkZoomLabelNode) zoomLabelNodeArray = np.where(zoomLabelNodeArray == 0, np.NAN, zoomLabelNodeArray) # Find index of Z axis slice with largest surface area in the label node maxZind = findLargestSurfaceAreaSlice(zoomLabelNodeArray) outputImage = modelHandler(zoomImageNode, zoomLabelNode, maxZind) writer=vtk.vtkPNGWriter() writer.SetFileName(outputImagePath) writer.SetInputData(outputImage) writer.Write() return(maxZind) except Exception, e: with open(progress_filename,mode='a') as printfile: printfile.write('ERROR: ' + str(e) + '\n\n') print "ERROR: Error Creating", outputImagePath, str(e) return(-1,-1,-1)
def picasaUploadPicture(self, snapshotNodeId, snapshotName, snapshotDescription, albumId, tags=[]): """Upload a snapshot node to the specified album, with a list of tags.""" self.checkLogin() if SlicerUtil.IsDevelopment: print ("Uploading image to Picasa") print ("Id: %s" % snapshotNodeId) print ("Name: %s" % snapshotName) print ("Description: %s" % snapshotDescription) print ("Album: %s" % albumId) print ("Tags:") print (tags) # time.sleep(3) # return snapshotNode = slicer.mrmlScene.GetNodeByID(snapshotNodeId) # Save the image to a temp file pngWriter = vtk.vtkPNGWriter() snapShotImage = snapshotNode.GetScreenShot() pngWriter.SetInputData(snapShotImage) filePath = "{0}/{1}.png".format(self.localStoragePath, snapshotName) pngWriter.SetFileName(filePath) pngWriter.Write() albumUrl = "/data/feed/api/user/default/albumid/" + albumId # Upload to Picasa self.gd_client.InsertPhotoSimple( albumUrl, snapshotName, snapshotDescription, filePath, content_type="image/png", keywords=tags )
def picasaUploadPicture(self, snapshotNodeId, snapshotName, snapshotDescription, albumId, tags=[]): """Upload a snapshot node to the specified album, with a list of tags.""" self.checkLogin() if (SlicerUtil.IsDevelopment): print ("Uploading image to Picasa") print(("Id: %s" % snapshotNodeId)) print(("Name: %s" % snapshotName)) print(("Description: %s" % snapshotDescription)) print(("Album: %s" % albumId)) print ("Tags:") print (tags) # time.sleep(3) # return snapshotNode = slicer.mrmlScene.GetNodeByID(snapshotNodeId) # Save the image to a temp file pngWriter = vtk.vtkPNGWriter() snapShotImage = snapshotNode.GetScreenShot() pngWriter.SetInputData(snapShotImage) filePath = "{0}/{1}.png".format(self.localStoragePath, snapshotName) pngWriter.SetFileName(filePath) pngWriter.Write() albumUrl = '/data/feed/api/user/default/albumid/' + albumId # Upload to Picasa self.gd_client.InsertPhotoSimple(albumUrl, snapshotName, snapshotDescription, filePath, content_type='image/png', keywords=tags)
def savePNGs(self, node, pattern): wlc = vtk.vtkImageMapToWindowLevelColors() wlc.SetInputData(node.GetImageData()) if not node.GetLabelMap(): displayNode = node.GetDisplayNode() wlc.SetWindow(displayNode.GetWindow()) wlc.SetLevel(displayNode.GetLevel()) wlc.Update() print(wlc.GetOutput().GetScalarRange()) cast = vtk.vtkImageCast() cast.SetInputConnection(wlc.GetOutputPort()) cast.SetOutputScalarTypeToUnsignedChar() pngWriter = vtk.vtkPNGWriter() pngWriter.SetFilePattern(pattern) pngWriter.SetInputConnection(cast.GetOutputPort()) pngWriter.Write() slicer.modules.BitmapGeneratorWidget.pngWriter = pngWriter
def ImageModelSnapshot(imageNode, labelNode, outputImagePath, progress_filename): castScalarToInt(imageNode) castScalarToInt(labelNode) # center label to origin of image, if needed #labelNode.SetOrigin(imageNode.GetOrigin()) try: minBounds, maxBounds = getCropBoundaries(labelNode) zoomImageNode = cropToZoom(imageNode, minBounds, maxBounds, label=False) zoomLabelNode = cropToZoom(labelNode, minBounds, maxBounds, label=True) sitkZoomLabelNode = su.PullFromSlicer(zoomLabelNode.GetName()) zoomLabelNodeArray = sitk.GetArrayFromImage(sitkZoomLabelNode) zoomLabelNodeArray = np.where(zoomLabelNodeArray == 0, np.NAN, zoomLabelNodeArray) # Find index of Z axis slice with largest surface area in the label node maxZind = findLargestSurfaceAreaSlice(zoomLabelNodeArray) outputImage = modelHandler(zoomImageNode, zoomLabelNode, maxZind) writer = vtk.vtkPNGWriter() writer.SetFileName(outputImagePath) writer.SetInputData(outputImage) writer.Write() return (maxZind) except Exception, e: with open(progress_filename, mode='a') as printfile: printfile.write('ERROR: ' + str(e) + '\n\n') print "ERROR: Error Creating", outputImagePath, str(e) return (-1, -1, -1)
def vtkImageDataToPNG(self, imageData, method='VTK'): """Return a buffer of png data using the data from the vtkImageData. """ if method == 'PIL': if imageData: imageData.Update() imageScalars = imageData.GetPointData().GetScalars() imageArray = vtk.util.numpy_support.vtk_to_numpy(imageScalars) d = imageData.GetDimensions() im = Image.fromarray( numpy.flipud(imageArray.reshape([d[1], d[0], 4]))) else: # no data available, make a small black opaque image a = numpy.zeros(100 * 100 * 4, dtype='uint8').reshape([100, 100, 4]) a[:, :, 3] = 255 im = Image.fromarray(a) #if size: #im.thumbnail((size,size), Image.ANTIALIAS) pngStringIO = StringIO.StringIO() im.save(pngStringIO, format="PNG") pngData = pngStringIO.getvalue() elif method == 'VTK': writer = vtk.vtkPNGWriter() writer.SetWriteToMemory(True) writer.SetInputDataObject(imageData) writer.SetCompressionLevel(0) writer.Write() result = writer.GetResult() pngArray = vtk.util.numpy_support.vtk_to_numpy(result) pngStringIO = StringIO.StringIO() pngStringIO.write(pngArray) pngData = pngStringIO.getvalue() return pngData
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 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 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()