1

我想在 python 中解压缩一批 nii.gz 文件,以便稍后在sitk 中处理它们。当我通过右键单击文件并选择“Extract..”手动解压缩单个文件时,该文件会被 sitk 正确解释(我做的是 sitk.ReadImage(unzipped))。但是当我尝试使用以下代码在 python 中解压缩它时:

with gzip.open(segmentation_zipped, "rb") as f:
    bindata = f.read()
segmentation_unzipped = os.path.join(segmentation_zipped.replace(".gz", ""))
with gzip.open(segmentation_unzipped, "wb") as f:
    f.write(bindata)

当 sitk 尝试读取文件时出现错误: RuntimeError: Exception throw in SimpleITK ReadImage: C:\d\VS14-Win64-pkg\SimpleITK\Code\IO\src\sitkImageReaderBase.cxx:82: sitk::ERROR: Unable确定“E:\BraTS19_2013_10_1_seg.nii”的 ImageIO 阅读器

同样,当尝试做一些不同的事情时:

input = gzip.GzipFile(segmentation_zipped, 'rb')
s = input.read()
input.close()

segmentation_unzipped = os.path.join(segmentation_zipped.replace(".gz", ""))
output = open(segmentation_unzipped, 'wb')
output.write(s)
output.close()

我得到: RuntimeError: Exception throw in SimpleITK ReadImage: C:\d\VS14-Win64-pkg\SimpleITK-build\ITK\Modules\IO\PNG\src\itkPNGImageIO.cxx:101: itk::ERROR: PNGImageIO(0000022E3AF2C0C0 ): PNGImageIO 未能读取文件头:原因:fread 只读 0 而不是 8

谁能帮忙?

4

1 回答 1

1

无需解压 Nifti 镜像,库等Nibabel无需解压即可处理。

#==================================
import nibabel as nib
import numpy as np
import matplotlib.pyplot as plt
#==================================
# load image (4D) [X,Y,Z_slice,time]
nii_img  = nib.load('path_to_file.nii.gz')
nii_data = nii_img.get_fdata()

fig, ax = plt.subplots(number_of_frames, number_of_slices,constrained_layout=True)
fig.canvas.set_window_title('4D Nifti Image')
fig.suptitle('4D_Nifti 10 slices 30 time Frames', fontsize=16)
#-------------------------------------------------------------------------------
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()

for slice in range(number_of_slices):
    # if your data in 4D, otherwise remove this loop
    for frame in range(number_of_frames):
        ax[frame, slice].imshow(nii_data[:,:,slice,frame],cmap='gray', interpolation=None)
        ax[frame, slice].set_title("layer {} / frame {}".format(slice, frame))
        ax[frame, slice].axis('off')

plt.show() 

或者您可以使用 SimpleITK,如下所示:

import SimpleITK as sitk
import numpy as np

# A path to a T1-weighted brain .nii image:
t1_fn = 'path_to_file.nii'

# Read the .nii image containing the volume with SimpleITK:
sitk_t1 = sitk.ReadImage(t1_fn)

# and access the numpy array:
t1 = sitk.GetArrayFromImage(sitk_t1)
于 2020-06-05T17:52:56.090 回答