niftiwrite changes the axis of 3D images

After performing some image processing in a 3D .nii format nifti image, I am using niftiwrite function to save it. But the nifti image is being saved in opposite axis like the anterior axis is being saved as posterior and vice versa, and the left to right ...
I am using itk-snap to visualize the saved image.

6 Comments

Hey guys,
this seems to be a bug that was fixed in 2020 (https://www.mathworks.com/matlabcentral/answers/511854-niftiread-niftiwrite-cycle-inappropriately-changes-image-orientation)
However, I do not have that version, so I tried to fix it myself. When I now open the nii in ITK Snap it shows correctly.
A is your volume
A = permute(A, [2,1,3]);
A = flip(A,3);
Hope this hleps
I have Matlab 2020b, and the bug is still not fixed.
The Matlab flips the signs of the quatern_b, quatern_c and quatern_d values in the raw nifty metadata.
See:
orig_info = niftiinfo(load_from_path)
orig_data = niftiread(load_from_path)
niftiwrite(orig_data, save_to_path, orig_info, 'Compressed', true)
tmp_info = niftiinfo(save_to_path)
% Compare these two:
orig_info.raw
tmp_info.raw
A "funny" work-around is to re-save the nifty (i.e., load the new created file and re-save it again) -- so the signs will be flipped back to the expected values.
It would be very nice from Matlab developers to fix this stupid bug... :-\
I'm running R2022a and this is still a bug...
The workaround of opening and resaving works well. Unfortunately, you have to view in the image viewer provided by MATLAB for it to show up properly. My other image viewing software (created by a member of my lab) doesn't handle this fix well.
I couldn't get the permute and flip functions working well, but I have 4D cine images that I'm working with.
Regardless, thank you for this answer. It helped me get out of a bind and the verbiage and code were concise and legible.
I tried load and re-save but it did not work. Permute and flip did not work either for me
Are you using info option when you use niftiwrite?You can get it using niftiinfo and then use it for niftiwrite.

Sign in to comment.

Answers (1)

2 Comments

Thanks for the tool but this does not answer the issue he was referring to
I have exactly the same problem. I would be grateful if someone finds a solution to this problem share it with me.

Sign in to comment.

Asked:

on 25 Aug 2019

Commented:

on 15 Jun 2023

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!