Avi*_*pta 17 python numpy image-processing matplotlib computer-vision
任何人都可以告诉我如何在python中读取包含.mhd / .raw文件的数据集?
sav*_*fod 17
最简单的方法是使用SimpleITK(MedPy也使用ITK作为.mhd/.raw文件).命令
pip install SimpleITK
Run Code Online (Sandbox Code Playgroud)
适用于许多python版本.对于阅读.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
Run Code Online (Sandbox Code Playgroud)
安装SimpleITK后,使用skimage可能会更容易
import skimage.io as io
img = io.imread('file.mhd', plugin='simpleitk')
Run Code Online (Sandbox Code Playgroud)
这将为您提供z,y,x排序的numpy数组.
添加上述帖子,您可以从从此处下载的 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()
Run Code Online (Sandbox Code Playgroud)
以下是读取并动画显示的相同 CT 扫描 .mhd 文件SimpleITK:
