@@ -281,6 +281,61 @@ the sform: ``get_qform()``, ``set_qform()``.
281281The qform also has a corresponding ``qform_code `` with the same interpretation
282282as the `sform_code `.
283283
284+ Default sform and qform codes
285+ =============================
286+
287+ If you create a new image, e.g.:
288+
289+ >>> data = np.random.random((20 , 20 , 20 ))
290+ >>> xform = np.eye(4 ) * 2
291+ >>> img = nib.nifti1.Nifti1Image(data, xform)
292+
293+ The sform and qform codes will be initialised to 2 (aligned) and 0 (unknown)
294+ respectively:
295+
296+ >>> img.get_sform(coded = True )
297+ (array([[ 2., 0., 0., 0.],
298+ [ 0., 2., 0., 0.],
299+ [ 0., 0., 2., 0.],
300+ [ 0., 0., 0., 1.]]), array(2, dtype=int16))
301+ >>> img.get_qform(coded = True )
302+ (None, 0)
303+
304+ This is based on the assumption that the affine you specify for a newly
305+ created image will align the image to some known coordinate system. According
306+ to the `NIfTI specification <nifti1 >`_, the qform is intended to encode a
307+ transformation into scanner coordinates - for a programmatically created
308+ image, we have no way of knowing what the scanner coordinate system is;
309+ furthermore, the qform cannot be used to store an arbitrary affine transform,
310+ as it is unable to encode shears. So the provided affine will be stored in the
311+ sform, and the qform will be left uninitialised.
312+
313+ If you create a new image and specify an existing header, e.g.:
314+
315+ >>> example_ni1 = os.path.join(data_path, ' example4d.nii.gz' )
316+ >>> n1_img = nib.load(example_ni1)
317+ >>> new_header = header= n1_img.header.copy()
318+ >>> new_data = np.random.random(n1_img.shape[:3 ])
319+ >>> new_img = nib.nifti1.Nifti1Image(data, None , header = new_header)
320+
321+ Then the newly created image will inherit the same sform and qform codes that
322+ are in the provided header. However, if you create a new image with both an
323+ affine and a header specified, e.g.:
324+
325+ >>> xform = np.eye(4 )
326+ >>> new_img = nib.nifti1.Nifti1Image(data, xform, header = new_header)
327+
328+ Then the sform and qform codes will *only * be preserved if the provided affine
329+ is the same as the affine in the provided header. If the affines do not match,
330+ the sform and qform codes will be set to their default values of 2 and 0
331+ respectively. This is done on the basis that, if you are changing the affine,
332+ you are likely to be changing the space to which the affine is pointing. So
333+ the original sform and qform codes can no longer be assumed to be valid.
334+
335+ If you wish to set the sform and qform affines and/or codes to some other
336+ value, you can always set them after creation using the ``set_sform `` and
337+ ``set_qform `` methods, as described above.
338+
284339The fall-back header affine
285340===========================
286341
0 commit comments