1212import numpy as np
1313
1414from ..funcs import concat_images , as_closest_canonical , OrientationError
15+ from ..analyze import AnalyzeImage
1516from ..nifti1 import Nifti1Image
1617from ..loadsave import save
1718
@@ -128,17 +129,40 @@ def test_concat():
128129
129130
130131def test_closest_canonical ():
131- arr = np .arange (24 ).reshape ((2 , 3 , 4 , 1 ))
132- # no funky stuff, returns same thing
132+ # Use 32-bit data so that the AnalyzeImage class doesn't complain
133+ arr = np .arange (24 ).reshape ((2 , 3 , 4 , 1 )).astype (np .int32 )
134+
135+ # Test with an AnalyzeImage first
136+ img = AnalyzeImage (arr , np .eye (4 ))
137+ xyz_img = as_closest_canonical (img )
138+ assert_true (img is xyz_img )
139+
140+ # And a case where the Analyze image has to be flipped
141+ img = AnalyzeImage (arr , np .diag ([- 1 , 1 , 1 , 1 ]))
142+ xyz_img = as_closest_canonical (img )
143+ assert_false (img is xyz_img )
144+ out_arr = xyz_img .get_data ()
145+ assert_array_equal (out_arr , np .flipud (arr ))
146+
147+ # Now onto the NIFTI cases (where dim_info also has to be updated)
148+
149+ # No funky stuff, returns same thing
133150 img = Nifti1Image (arr , np .eye (4 ))
151+ # set freq/phase/slice dim so that we can check that we
152+ # re-order them properly
153+ img .header .set_dim_info (0 , 1 , 2 )
134154 xyz_img = as_closest_canonical (img )
135155 assert_true (img is xyz_img )
156+
136157 # a axis flip
137158 img = Nifti1Image (arr , np .diag ([- 1 , 1 , 1 , 1 ]))
159+ img .header .set_dim_info (0 , 1 , 2 )
138160 xyz_img = as_closest_canonical (img )
139161 assert_false (img is xyz_img )
162+ assert_true (img .header .get_dim_info () == xyz_img .header .get_dim_info ())
140163 out_arr = xyz_img .get_data ()
141164 assert_array_equal (out_arr , np .flipud (arr ))
165+
142166 # no error for enforce_diag in this case
143167 xyz_img = as_closest_canonical (img , True )
144168 # but there is if the affine is not diagonal
@@ -150,3 +174,22 @@ def test_closest_canonical():
150174 assert_true (img is xyz_img )
151175 # it's still not diagnonal
152176 assert_raises (OrientationError , as_closest_canonical , img , True )
177+
178+ # an axis swap
179+ aff = np .diag ([1 , 0 , 0 , 1 ])
180+ aff [1 , 2 ] = 1 ; aff [2 , 1 ] = 1
181+ img = Nifti1Image (arr , aff )
182+ img .header .set_dim_info (0 , 1 , 2 )
183+
184+ xyz_img = as_closest_canonical (img )
185+ assert_false (img is xyz_img )
186+ # Check both the original and new objects
187+ assert_true (img .header .get_dim_info () == (0 , 1 , 2 ))
188+ assert_true (xyz_img .header .get_dim_info () == (0 , 2 , 1 ))
189+ out_arr = xyz_img .get_data ()
190+ assert_array_equal (out_arr , np .transpose (arr , (0 , 2 , 1 , 3 )))
191+
192+ # same axis swap but with None dim info (except for slice dim)
193+ img .header .set_dim_info (None , None , 2 )
194+ xyz_img = as_closest_canonical (img )
195+ assert_true (xyz_img .header .get_dim_info () == (None , None , 1 ))
0 commit comments