简体   繁体   English

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

[英]Reading *.mhd/*.raw format in python

任何人都可以告诉我如何在python中读取包含.mhd / .raw文件的数据集?

The easiest way is to use SimpleITK (MedPy uses ITK for .mhd/.raw files too). 最简单的方法是使用SimpleITK (MedPy也使用ITK作为.mhd / .raw文件)。 Command 命令

pip install SimpleITK

works for many python versions. 适用于许多python版本。 For reading .mhd/.raw you can use this code from kaggle 对于阅读.mhd / .raw,您可以使用来自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

Using skimage may be even easier after you installed SimpleITK 安装SimpleITK后,使用skimage可能会更容易

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

This will give you a numpy array with z,y,x sorting. 这将为您提供z,y,x排序的numpy数组。

Adding on the above posts, you can start with a CT-Scan .mhd file downloaded from the here and display / save 29 images with the following code (assuming that you have both the header and the raw files downloaded in the current directory): 添加上述帖子,您可以从此处下载的CT-Scan .mhd文件开始,并使用以下代码显示/保存29个图像(假设您在当前目录中同时下载了标题和原始文件):

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()

在此输入图像描述

Here is the same CT-scan .mhd file that is read with SimpleITK and animated: 这是使用SimpleITK和动画读取的相同CT扫描.mhd文件: 在此输入图像描述

You can try to use MedPy or this mhd_utils script 您可以尝试使用MedPy或此mhd_utils脚本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM