我正在嘗試在重塑影像后對其進行重塑,但在保存方法方面我遇到了問題。這是我要運行的代碼:
import nibabel as nib
import numpy as np
from nibabel.testing import data_path
import os
example_filename = os.path.join("D:/Volumes convertidos LIDC",
'teste001converted.nii.gz')
img = nib.load('teste001converted.nii.gz')
print (img.shape)
newimg = img.get_fdata().reshape(332,360*360)
print (newimg.shape)
final_img = nib.Nifti1Image(newimg, img.affine)
nib.save(final_img, os.path.join("D:/Volumes convertidos LIDC",
'test2d.nii.gz'))
我收到一個錯誤:
(最近一次通話最后):
檔案“d:\Volumes convertidos LIDC\reshape.py”,第 17 行,在 final_img = nib.Nifti1Image(newimg, img.affine)
檔案“C:\Python39\lib\site-packages\nibabel\nifti1.py”,第 1756 行,在init super(Nifti1Pair, self) 中。初始化(資料物件,
檔案“C:\Python39\lib\site-packages\nibabel\analyze.py”,第 918 行,在init super(AnalyzeImage, self) 中。init(檔案“C:\Python39\lib\site-packages\nibabel\spatialimages.py”,第 469 行,在init self.update_header()
檔案“C:\Python39\lib\site-packages\nibabel\nifti1.py”,第 2032 行,在 update_header super(Nifti1Image, self).update_header() 檔案“C:\Python39\lib\site-packages\nibabel\ nifti1.py",第 1795 行,在 update_header super(Nifti1Pair, self).update_header()
檔案“C:\Python39\lib\site-packages\nibabel\spatialimages.py”,第 496 行,在 update_header hdr.set_data_shape(shape)
檔案“C:\Python39\lib\site-packages\nibabel\nifti1.py”,第 880 行,在 set_data_shape super(Nifti1Header, self).set_data_shape(shape)
檔案“C:\Python39\lib\site-packages\nibabel\analyze.py”,第 633 行,在 set_data_shape
raise HeaderDataError(f'shape {shape} does not fit in dim datatype')
nibabel.spatialimages.HeaderDataError: shape (332, 129600) 不適合 dim 資料型別
有什么辦法可以解決嗎?
uj5u.com熱心網友回復:
您正在嘗試保存一個numpy陣列,而nib.save期望一個SpatialImage物件。
您應該將numpy陣列轉換為SpatialImage:
final_img = nib.Nifti1Image(newimg, img.affine)
之后您可以保存影像:
nib.save(final_img, os.path.join("D:/Volumes convertidos LIDC", 'test4d.nii.gz'))
有關更多說明,請參閱檔案和此答案。
編輯:newimg如果是 2D 影像,這將不起作用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/410288.html
標籤:
