在Slicer中创建vtkMRMLScalarVolumeNode

本文介绍了一种使用Python脚本在Slicer中加载体数据的方法。通过设置体数据的各项属性,如尺寸、原点、间隔和方向,并利用numpy与VTK的支持,成功将数据转换并展示在Slicer中。
部署运行你感兴趣的模型镜像

目的:
平常为了将体数据显示到Slicer中,可以直接把体数据拖到Slicer中进行显示
在这里插入图片描述
现在是准备用代码将体数据显示到Slicer中

import logging
import os

import vtk
import slicer
from slicer.ScriptedLoadableModule import *
from slicer.util import VTKObservationMixin
import numpy as np     



class Test(ScriptedLoadableModule):
    """Uses ScriptedLoadableModule base class, available at:
    https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
    """

    def __init__(self, parent):
        ScriptedLoadableModule.__init__(self, parent)
        self.parent.title = "Test"  # TODO: make this more human readable by adding spaces
        self.parent.categories = ["Examples"]  # TODO: set categories (folders where the module shows up in the module selector)
        self.parent.dependencies = []  # TODO: add here list of module names that this module requires
        self.parent.contributors = ["John Doe (AnyWare Corp.)"]  # TODO: replace with "Firstname Lastname (Organization)"
        # TODO: update with short description of the module and a link to online module documentation
        self.parent.helpText = """
This is an example of scripted loadable module bundled in an extension.
See more information in <a href="https://github.com/organization/projectname#Test">module documentation</a>.
"""
        # TODO: replace with organization, grant and thanks
        self.parent.acknowledgementText = """
This file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc., Andras Lasso, PerkLab,
and Steve Pieper, Isomics, Inc. and was partially funded by NIH grant 3P41RR013218-12S1.
"""

class TestWidget(ScriptedLoadableModuleWidget, VTKObservationMixin):
    """Uses ScriptedLoadableModuleWidget base class, available at:
    https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
    """

    def __init__(self, parent=None):
        """
        Called when the user opens the module the first time and the widget is initialized.
        """
        ScriptedLoadableModuleWidget.__init__(self, parent)
        VTKObservationMixin.__init__(self)  # needed for parameter node observation
        self.logic = None
        self._parameterNode = None
        self._updatingGUIFromParameterNode = False

    def setup(self):
        """
        Called when the user opens the module the first time and the widget is initialized.
        """
        ScriptedLoadableModuleWidget.setup(self)

        import qt
        
        imageData = vtk.vtkImageData()
        #imageSize、imageOrigin、imageSpacing和imageDirections这些信息都可以在Slicer中的Volume模块中看到
        imageSize = [256,256,112  ]
        imageOrigin = [119.531,119.531,-77.7]
        imageSpacing=[0.9375,0.9375,1.4000]
        imageDirections = [[-1,0,0], [0,-1,0], [0,0,1]]

        #设定Dimension
        imageData.SetDimensions(imageSize)
        #数据的类型是int,因为是标量数据,所以填1
        imageData.AllocateScalars(vtk.VTK_FLOAT, 1)

        brainDataArray=np.load("/home/chenxiaohui/tmp/brainData.npy")
        data_vtk = vtk.util.numpy_support.numpy_to_vtk(brainDataArray.ravel(),array_type=vtk.VTK_FLOAT)
        imageData.GetPointData().SetScalars(data_vtk)

        referenceVolumeNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLScalarVolumeNode")
        referenceVolumeNode.SetOrigin(imageOrigin)
        referenceVolumeNode.SetSpacing(imageSpacing)
        referenceVolumeNode.SetAndObserveImageData(imageData)
        referenceVolumeNode.SetName("brain")
        referenceVolumeNode.SetIJKToRASDirections(imageDirections)

效果

在这里插入图片描述

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

<think>我们正在讨论3D SlicerPython控制台的使用方法。根据用户之前的查询和提供的引用,用户希望了解如何在3D Slicer中使用Python控制台。参考引用[1][2][3]中的信息,我们可以总结如下: 引用[1]提到可以使用`with slicer.util.RenderBlocker():`来阻止渲染,从而在执行多个操作时提高性能。 引用[2]说明了如何从Python控制台启动Jupyter内核,以便使用Jupyter Notebook连接和控制3D Slicer。 引用[3]则提到了在Slicer中编程,包括Module Widget(GUI)、Module Logic(处理逻辑)和Module Test(自动测试)等概念。 因此,我们可以将回答分为几个部分: 1. 如何打开Python控制台 2. Python控制台的基本功能 3. 使用Python控制台执行常见任务(包括引用[1]中提到的渲染阻塞) 4. 如何与Jupyter Notebook连接(引用[2]) 5. 如何通过Python控制台编写和测试模块(引用[3]) 由于引用[1][2][3]都与3D SlicerPython接口相关,我们可以将其作为参考整合到回答中。 下面按照结构化方式回答: </think>### SlicerPython控制台的使用方法 以下是3D SlicerPython控制台的核心使用方法和技巧: #### 1. **打开Python控制台** - 菜单路径:`View → Python Console` - 快捷键:`Ctrl+3`(Windows/Linux)或`Command+3`(Mac) - 界面位置:默认出现在主界面底部面板 #### 2. **基础操作** ```python # 示例1:创建球体并设置属性 sphere = slicer.modules.models.logic().AddSphere(10.0) # 创建半径10mm的球体[^3] sphere.GetDisplayNode().SetColor(1,0,0) # 设置为红色 # 示例2:加载DICOM数据 volumeNode = slicer.util.loadVolume("path/to/dicom_data") # 加载医学影像数据 ``` - 支持Tab键自动补全功能(输入`slicer.`后按Tab查看所有模块) - 使用`dir(object)`查看对象可用属性和方法 #### 3. **高级功能** **a. 渲染控制**(引用[1]示例) ```python with slicer.util.RenderBlocker(): # 执行批量操作时不触发实时渲染 for i in range(100): sphere.SetPosition(i,0,0) ``` **b. 连接Jupyter Notebook**(引用[2]方法) ```python # 在Python控制台执行 connection_file = r'C:\path\to\kernel-xxxx.json' slicer.modules.jupyterkernel.startKernel(connection_file) ``` > 启动后可在Jupyter中通过`import slicer`远程控制Slicer **c. 模块开发调试** ```python # 创建测试模块(引用[3]概念) widget = slicer.qSlicerPythonModuleWidget() widget.setup() widget.show() ``` #### 4. **实用技巧** - **数据加载**: ```python # 从URL加载测试数据 slicer.util.TESTING_DATA_URL = 'https://github.com/Slicer/SlicerTestingData/releases/download/' test_volume = slicer.util.downloadAndLoadFile(f"{slicer.util.TESTING_DATA_URL}MRHead.nrrd")[^1] ``` - **事件监听**: ```python def onSceneClosed(caller,event): print("场景已关闭!") slicer.mrmlScene.AddObserver(slicer.vtkMRMLScene.EndCloseEvent, onSceneClosed) ``` - **批量处理**: ```python # 遍历所有体积节点 for vol in slicer.util.getNodesByClass("vtkMRMLScalarVolumeNode"): print(f"处理体积: {vol.GetName()}") ``` #### 5. **调试与错误处理** - 使用`print()`输出调试信息 - 异常捕获: ```python try: slicer.util.loadModel("invalid_path.stl") except Exception as e: print(f"加载失败: {str(e)}") ``` - 重置环境:`slicer.mrmlScene.Clear(0)` 清除当前场景 > **重要提示**:所有操作会实时修改Slicer场景,建议复杂操作前先保存工程(`slicer.util.saveScene("backup.mrb")`)。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值