写一段代码 要求能用PyQt结合VTK读取指定的.dcm文件,将其转换成.nii.gz文件并做三维可视化
时间: 2024-05-10 12:21:25 浏览: 164
VTK读取.vtk格式文件,并3维显示
4星 · 用户满意度95%
以下是一个示例代码,可以使用PyQt和VTK读取指定的.dcm文件,将其转换为.nii.gz文件,并进行三维可视化:
```python
import vtk
import numpy as np
import SimpleITK as sitk
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QWidget, QVBoxLayout
from vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("DICOM to NIFTI Converter and Viewer")
self.setGeometry(100, 100, 800, 600)
self.central_widget = QWidget(self)
self.setCentralWidget(self.central_widget)
self.vtk_widget = QVTKRenderWindowInteractor(self.central_widget)
self.layout = QVBoxLayout(self.central_widget)
self.layout.addWidget(self.vtk_widget)
self.reader = vtk.vtkDICOMImageReader()
self.renderer = vtk.vtkRenderer()
self.vtk_widget.GetRenderWindow().AddRenderer(self.renderer)
self.renWin = self.vtk_widget.GetRenderWindow()
self.interactor = self.renWin.GetInteractor()
self.interactor.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
self.interactor.SetRenderWindow(self.renWin)
self.file_dialog = QFileDialog(self.central_widget)
self.file_dialog.setNameFilter("DICOM files (*.dcm)")
self.file_dialog.fileSelected.connect(self.load_dicom)
self.menu_bar = self.menuBar()
self.file_menu = self.menu_bar.addMenu("File")
self.open_file_action = self.file_menu.addAction("Open DICOM file")
self.open_file_action.triggered.connect(self.file_dialog.exec_)
self.convert_to_nifti_action = self.file_menu.addAction("Convert to NIFTI")
self.convert_to_nifti_action.triggered.connect(self.convert_to_nifti)
def load_dicom(self, filename):
self.reader.SetDirectoryName(filename)
self.reader.Update()
image_data = self.reader.GetOutput()
extent = image_data.GetExtent()
mapper = vtk.vtkFixedPointVolumeRayCastMapper()
mapper.SetInputData(image_data)
volume = vtk.vtkVolume()
volume.SetMapper(mapper)
self.renderer.AddVolume(volume)
self.renderer.ResetCamera()
self.renWin.Render()
def convert_to_nifti(self):
filename, _ = self.file_dialog.getSaveFileName(self.central_widget, "Save NIFTI file", "", "NIFTI files (*.nii.gz)")
if filename:
image_data = self.reader.GetOutput()
array = vtk.util.numpy_support.vtk_to_numpy(image_data.GetPointData().GetScalars())
array = np.reshape(array, image_data.GetDimensions(), order='F')
sitk_image = sitk.GetImageFromArray(array)
sitk_image.SetSpacing(image_data.GetSpacing())
sitk_image.SetOrigin(image_data.GetOrigin())
sitk_image.SetDirection(image_data.GetDirection())
sitk.WriteImage(sitk_image, filename)
print("Converted to NIFTI:", filename)
if __name__ == "__main__":
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
```
运行此代码后,将打开一个具有菜单栏的窗口。单击“文件”菜单中的“打开DICOM文件”选项,选择要加载的.dcm文件。加载DICOM文件后,将在窗口中显示三维可视化。单击“文件”菜单中的“转换为NIFTI”选项,选择要将DICOM文件转换为的.nii.gz文件的路径。转换完成后,将在控制台中显示“已转换为NIFTI:”和文件路径。
阅读全文