在 python 中读取 *.mhd/*.raw 格式

Reading *.mhd/*.raw format in python

谁能告诉我如何读取包含 .mhd/.raw 文件的数据集 python?

你可以尝试使用MedPy or this mhd_utils script

最简单的方法是使用 SimpleITK(MedPy 也对 .mhd/.raw 文件使用 ITK)。命令

pip install SimpleITK

适用于许多 python 版本。要阅读 .mhd/.raw,您可以使用此代码 from kaggle

import SimpleITK as sitk
import numpy as np
'''
This funciton reads a '.mhd' file using SimpleITK and return the image array, origin and spacing of the image.
'''

def load_itk(filename):
    # Reads the image using SimpleITK
    itkimage = sitk.ReadImage(filename)

    # Convert the image to a  numpy array first and then shuffle the dimensions to get axis in the order z,y,x
    ct_scan = sitk.GetArrayFromImage(itkimage)

    # Read the origin of the ct_scan, will be used to convert the coordinates from world to voxel and vice versa.
    origin = np.array(list(reversed(itkimage.GetOrigin())))

    # Read the spacing along each dimension
    spacing = np.array(list(reversed(itkimage.GetSpacing())))

    return ct_scan, origin, spacing

安装 SimpleITK 后使用 skimage 可能会更容易

import skimage.io as io
img = io.imread('file.mhd', plugin='simpleitk')

这将为您提供一个按 z,y,x 排序的 numpy 数组。

添加以上帖子,您可以从 here 下载的 CT-Scan .mhd 文件开始,并使用以下代码显示/保存 29 张图像(假设您同时拥有 header和当前目录下下载的原始文件):

import SimpleITK as sitk
import matplotlib.pylab as plt
ct_scans = sitk.GetArrayFromImage(sitk.ReadImage("training_001_ct.mhd", sitk.sitkFloat32))
plt.figure(figsize=(20,16))
plt.gray()
plt.subplots_adjust(0,0,1,1,0.01,0.01)
for i in range(ct_scans.shape[0]):
    plt.subplot(5,6,i+1), plt.imshow(ct_scans[i]), plt.axis('off')
    # use plt.savefig(...) here if you want to save the images as .jpg, e.g.,
plt.show()

这是使用 SimpleITK 读取并设置动画的同一个 CT-scan .mhd 文件: