python显示dicom数据

最近在看python, 写段显示dicom的代码,练练手。

#!C:\Program Files\Python\Python38\Python

import numpy as np
import matplotlib.pyplot as plt
import vtk
from vtk.util.numpy_support import vtk_to_numpy

class  dicom2dviewer():
    def __init__(self):
        self.data = np.array([])
        self.srcdata = []
        self.tardata = np.array([])
        self.dims = []
        self.spacing = []
        self.curindex = 0
        self.fig = None

        self.arrX = []
        self.arrY = []


    def __loadDicom(self, path):
        reader = vtk.vtkDICOMImageReader()
        reader.SetDirectoryName(path)
        reader.Update()

        extent = reader.GetDataExtent()
        self.dims = [extent[1] - extent[0] + 1, extent[3] - extent[2] + 1, extent[5] - extent[4] +1];
        self.spacing = reader.GetPixelSpacing()

        imageData = reader.GetOutput()
        self.srcdata = imageData.GetPointData().GetArray(0)
        self.tardata = vtk_to_numpy(self.srcdata)
        self.tardata = self.tardata.reshape((self.dims[2], self.dims[0], self.dims[1]), order='C')

        self.arrX = np.arange(0, self.dims[0]+1, 1)
        self.arrY = np.arange(0, self.dims[1]+1, 1)

    def show(self, path):
        self.__loadDicom(path)

        plt.set_cmap(plt.gray())
        self.fig = plt.gcf()
        self.__update(self.curindex)
        self.fig.canvas.mpl_connect('scroll_event', self.__onMouseWheelEvent)
        self.fig.canvas.mpl_connect('motion_notify_event', self.__onMouseEvent)
        plt.show()

    def __update(self, index):
        if(index >= 0 and index < self.dims[2]):
            plt.pcolormesh(self.arrX, self.arrY, self.tardata[index, :, :])
            self.fig.canvas.draw_idle()

    def __onMouseWheelEvent(self, event):
        if("up" == event.button):
            self.curindex = self.curindex - 1
        else:      
            self.curindex = self.curindex + 1

        if(self.curindex < 0):
            self.curindex = 0
        elif (self.curindex >= self.dims[2]):
            self.curindex = self.dims[2] - 1

        self.__update(self.curindex)

    def __onMouseEvent(self, event):
        info = 'x:{} y:{}'.format(event.xdata, event.ydata)
        #print(info)

使用方法:dicom2dviewer().show(dicom路径)

你可能感兴趣的:(Dicom,python)