我正在编写一个可以估计 3d Nifti(.nii) 图像清晰度的脚本。在我的方法中,我需要先取出它的 xz(axis) 切片,然后将其保存为 .png 文件。(为了提高效率,只取一个)然后,估计图像的清晰度。但是,我不知道如何用特定平面(切片)切片 3d 图像。是否有任何现有的代码或库可以进行切片?
我正在使用 Python 3.7(在 Window 10 中运行)。
我试过这个库:https ://pypi.org/project/nii2png/ 但是,它不能输出单个硅片。
我也试过这个页面的方法 https://nipy.org/nibabel/coordinate_systems.html#introducing-someone 但是,它不起作用。原因可能是 Nifti 文件不同。我认为有两种 nifti 格式的文件。
import nibabel as nib
import numpy as np
import matplotlib.pyplot as plt
def show_slices(slices):
""" Function to display row of image slices """
fig, axes = plt.subplots(1, len(slices))
for i, slice in enumerate(slices):
axes[i].imshow(slice.T, cmap="gray", origin="lower")
data = nib.load('D:\\Work\\Script\\__Project\\s\\ADNI\\good_img\\MPRAGE_SENSE2\\2012-11-08_07_32_36.0\\S174286\\ADNI_002_S_5018_MR_MPRAGE_SENSE2__br_raw_20121112145413785_28_S174286_I346236.nii')
data.get_fdata()
data = data.get_fdata()
data.shape
#d_data = np.delete(data, 3, 0) #doesn't work, because it's object of type 'Nifti1Image'
#matplotlib inline
#plt.imshow(data.get_data()[:,:,50])
plt.plot(np.mean(data,axis=(0,1,2)))
plt.show()
slice_0 = data[26, :, :, :]
slice_1 = data[:, 30, :, :]
slice_2 = data[:, :, 16, :]
slice_3 = data[:, :, :, 0]
show_slices([slice_0, slice_1, slice_2, slice_3])
plt.suptitle("Center slices for EPI image")
然后我得到错误:
Warning (from warnings module):
File "D:\Program_Files_2\Python\lib\site-packages\dicom\__init__.py", line 53
warnings.warn(msg)
UserWarning:
This code is using an older version of pydicom, which is no longer
maintained as of Jan 2017. You can access the new pydicom features and API
by installing `pydicom` from PyPI.
See 'Transitioning to pydicom 1.x' section at pydicom.readthedocs.org
for more information.
Traceback (most recent call last):
File "D:\Work\Script\__Project\s\try_load_nii_image_and_view_slice_3.py", line 25, in <module>
show_slices([slice_0, slice_1, slice_2, slice_3])
File "D:\Work\Script\__Project\s\try_load_nii_image_and_view_slice_3.py", line 9, in show_slices
axes[i].imshow(slice.T, cmap="gray", origin="lower")
File "D:\Program_Files_2\Python\lib\site-packages\matplotlib\__init__.py", line 1601, in inner
return func(ax, *map(sanitize_sequence, args), **kwargs)
File "D:\Program_Files_2\Python\lib\site-packages\matplotlib\cbook\deprecation.py", line 369, in wrapper
return func(*args, **kwargs)
File "D:\Program_Files_2\Python\lib\site-packages\matplotlib\cbook\deprecation.py", line 369, in wrapper
return func(*args, **kwargs)
File "D:\Program_Files_2\Python\lib\site-packages\matplotlib\axes\_axes.py", line 5671, in imshow
im.set_data(X)
File "D:\Program_Files_2\Python\lib\site-packages\matplotlib\image.py", line 690, in set_data
.format(self._A.shape))
TypeError: Invalid shape (1, 256, 256) for image data