I'm trying to convert a .npy
image to a nii.gz
image, I'm having various problems even though I'm following instructions correctly.
This is the code I'm using:
import numpy as np
import nibabel as nib
file_dir = "D:/teste volumes slicer/"
fileNPY1 = "teste01.npy"
img_array1 = np.load(file_dir fileNPY1)
print(img_array1.shape)
print(img_array1.dtype)
normal_array = "D:/teste volumes slicer/teste01.npy"
print ("done")
nifti_file = nib.Nifti1Image(normal_array, np.eye(4))
About the image: (332, 360, 360) float64 (this is what we got when we print the shape and dtype) https://ibb.co/mRyTrw7 - image that shows the error and the image's information
The error message:
Traceback (most recent call last):
File "d:\teste volumes slicer\conversor.py", line 16, in <module>
nifti_file = nib.Nifti1Image(normal_array, np.eye(4))
File "C:\Python39\lib\site-packages\nibabel\nifti1.py", line 1756, in __init__
super(Nifti1Pair, self).__init__(dataobj,
File "C:\Python39\lib\site-packages\nibabel\analyze.py", line 918, in __init__
super(AnalyzeImage, self).__init__(
File "C:\Python39\lib\site-packages\nibabel\spatialimages.py", line 469, in __init__
self.update_header()
File "C:\Python39\lib\site-packages\nibabel\nifti1.py", line 2032, in update_header
super(Nifti1Image, self).update_header()
File "C:\Python39\lib\site-packages\nibabel\nifti1.py", line 1795, in update_header
super(Nifti1Pair, self).update_header()
File "C:\Python39\lib\site-packages\nibabel\spatialimages.py", line 491, in update_header
shape = self._dataobj.shape
AttributeError: 'str' object has no attribute 'shape'
CodePudding user response:
The problem with your code is instead of passing your Numpy-array (your image), you are passing the path of the image to the Nifti1Image
function.
This is the correct way to convert it:
import numpy as np
import nibabel as nib
file_dir = "D:/teste volumes slicer/"
fileNPY1 = "teste01.npy"
img_array1 = np.load(file_dir fileNPY1)
nifti_file = nib.Nifti1Image(img_array1 , np.eye(4))