【发布时间】:2016-09-14 09:50:26
【问题描述】:
谁能告诉我如何在 python 中读取包含 .mhd/.raw 文件的数据集?
【问题讨论】:
标签: python numpy matplotlib image-processing computer-vision
谁能告诉我如何在 python 中读取包含 .mhd/.raw 文件的数据集?
【问题讨论】:
标签: python numpy matplotlib image-processing computer-vision
最简单的方法是使用SimpleITK(MedPy 也将 ITK 用于 .mhd/.raw 文件)。命令
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 张图像(假设您在当前目录):
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()
【讨论】:
你可以尝试使用MedPy或者这个mhd_utils script
【讨论】: