簡體   English   中英

使用 python 解壓 gz 格式的 nifti 醫學圖像

[英]Decompress nifti medical image in gz format using python

我想解壓縮 python 中的一堆 nii.gz 文件,以便稍后在現場處理它們。 當我通過右鍵單擊文件並選擇“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:SimpleITK ReadImage 中引發的異常:C:\d\VS14-Win64-pkg\SimpleITK-build\ITK\Modules\IO\PNG\src\itkPNGImageIO.cxx:101: itk::ERROR: PNGImageIO(0000022E3AF2C0C0 ):PNGImageIO 無法讀取 header 文件:原因:fread 只讀 0 而不是 8

誰能幫忙?

無需解壓 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM