【问题标题】:How can I save an image (nii.gz) after reshaping it?重塑图像后如何保存图像(nii.gz)?
【发布时间】:2022-01-12 17:26:55
【问题描述】:

我正在尝试在重塑图像后对其进行重塑,但在保存方法方面我遇到了问题。这是我要运行的代码:

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)

init 中的文件“C:\Python39\lib\site-packages\nibabel\nifti1.py”,第 1756 行 super(Nifti1Pair, self).init(dataobj,

init 中的文件“C:\Python39\lib\site-packages\nibabel\analyze.py”,第 918 行 super(AnalyzeImage, self).init( init 中的文件“C:\Python39\lib\site-packages\nibabel\spatialimages.py”,第 469 行 self.update_header()

文件“C:\Python39\lib\site-packages\nibabel\nifti1.py”,第 2032 行,在 update_header 中 超级(Nifti1Image,自我).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 数据类型

有什么办法可以解决吗?

【问题讨论】:

  • 我认为不应将此问题标记为重复问题。就我而言,在 SO 的任何其他问题中都没有提到这个特定的错误消息。
  • 请将代码和数据添加为文本 (using code formatting),而不是图像。图片:A)不允许我们复制粘贴代码/错误/数据进行测试; B) 不允许根据代码/错误/数据内容进行搜索;和many more reasons。除了代码格式的文本之外,只有在图像添加了一些重要的东西,而不仅仅是文本代码/错误/数据传达的内容时,才应该使用图像。
  • 我刚刚改了,谢谢@gre_gor

标签: python image numpy


【解决方案1】:

您正在尝试保存 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'))

请参阅documentation 和此answer 了解更多说明。

编辑:如果 newimg 是 2D 图像,这将不起作用。

【讨论】:

  • 感谢您的输入,很遗憾您的解决方案不起作用,我收到此错误:HeaderDataError: shape (332, 129600) does not fit in dim datatype
  • @MauricésarBarbosa 请编辑您的问题并添加完整的代码和错误,以便我检查。
  • 我刚刚做了@A.Najafi
  • 您已加载 3D 图像并将其重新塑造成 2D 图像。这可能是问题所在。显然,要么NiftiImage不接受2D图像,要么img.affine有一些与newimg不匹配的3D信息。
  • 以下 NiBabel 教程明确指出:“图像数据数组:图像数据的 3D 或 4D 数组。” nipy.org/nibabel/coordinate_systems.html
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-01
  • 2020-06-25
  • 2016-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-14
相关资源
最近更新 更多