The NIfTI-1 Data Format

NIfTI-1 FAQ

NIfTI-1 overview chart

Data dimensionality

The NIfTI-1 header

Extending a NIfTI-1 file

NIfTI-1 Statistical parametric data

Other data intentions in NIfTI-1

Data transformations

Introduction

NIfTI-1 is a somewhat new data format, proposed by the NIfTI DFWG as a short-term measure to facilitate inter-operation of functional MRI data analysis software packages. It is adapted from the widely used ANALYZETM 7.5 file format. The hope is that older non-NIfTI-aware software that uses the ANALYZE 7.5 format will still be compatible with NIfTI-1. NIfTI-1 uses the "empty space" in the ANALYZE 7.5 header to add several new features. These features are described in the current document.

NIfTI-1 flag (magic strings)

To flag such a struct as being conformant to the NIFTI-1 spec, the last 4 bytes of the header must be either the C String ”ni1” or ”n+1”; in hexadecimal, the

4 bytes 6E 69 31 00 or 6E 2B 31 00 (in any future version of this format, the ’1’ will be upgraded to ’2’, etc.). Normally, such a ”magic number” or flag goes

at the start of the file, but trying to avoid clobbering widely-used ANALYZE 7.5 fields led to putting this marker last. However, recall that ”the last shall be

first” (Matthew 20:16).

If a NIFTI-aware program reads a header file that is NOT marked with a NIFTI magic string, then it should treat the header as an ANALYZE 7.5 structure.

NIfTI-1 file storage

”ni1” means that the image data is stored in the ”.img” file corresponding to the header file (starting at file offset 0).

”n+1” means that the image data is stored in the same file as the header information.

We recommend that the combined header+data filename should be ”.nii”. When the dataset is stored in one file, the first byte of image data is

stored at byte location (int)vox_offset in this combined file.

Grace under fire

Most NIFTI-aware programs will only be able to handle a subset of the full range of datasets possible with this format. All NIFTI-aware programs should

take care to check if an input dataset conforms to the program’s needs and expectations (e.g., check datatype, intent_code, etc.). If the input dataset can’t

be handled by the program, the program should fail gracefully (e.g., print a useful warning; not crash).

This information is provided in the nifti-1.h code by Robert W. Cox (NIH)

.


NIfTI-1 FAQ nocss

NIfTI-1 FAQ List
Brought to you by the members of the Data Format Working Group

  • Q1. What are NIfTI and the DFWG?
  • Q2. Why didn't the committee choose the DICOM format? The MINC-2 format?
  • Q3. Can you add my favorite variable X to the header?
  • Q4. What is the minimum set of fields required to create a NIfTI-1 header?
  • Q5. What format converters are available?
  • Q6. What I/O libraries are available?
  • Q7. How do I tell if an ANALYZETM 7.5 header is NIfTI-1 compatible?
  • Q8. Is NIfTI-1 compatible with the ANALYZE 7.5 file format?
  • Q9. Do I need to convert all of my files to this format?
  • Q10. Is the NIfTI-1 header extensible?
  • Q11. What modalities does this format support?
  • Q12. What types of data can I store in the format?
  • Q13. Does NIfTI-1 solve the problem of data interchange in fMRI?
  • Q14. What is the default orientation?
  • Q15. Is the default radiological or neurological orientation?
  • Q16. What is a quaternion?
  • Q17. What alignment information is stored in the NIfTI-1 header?
  • Q18. Does NIfTI-1 support a single file format for header and data?
Q1. What are NIfTI and the DFWG? (Mike Huerta)

The purpose of the Neuroimaging Informatics Technology Initiative (NIfTI) is to support service, training, and research to develop and enhance the utility of informatics tools used in neuroimaging, with a focus on functional magnetic resonance imaging (fMRI). NIfTI is jointly sponsored by the National Institute of Mental Health (NIMH) and the National Institute of Neurological Disorders and Stroke (NINDS), which are part of the National Institutes of Health (NIH) and the Department of Health and Human Services (DHHS). Further background can be found at this link. NIfTI was developed and has been implemented with input from the community of neuroscientists who use neuroimaging in their research, and from the community of developers of informatics tools used to make sense of neuroimaging data (with an emphasis on fMRI).

There are two major activities of NIfTI, thus far. The first is the support of a cluster of grants to characterize, compare, and validate informatics tools used in fMRI studies.

The second is the support of the Data Format Working Group. The DFWG is charged with arriving at a technical solution to the problem of multiple data formats used in fMRI research. This was identified by many investigators as a fundamental obstacle to fMRI fulfilling the promise it has to elucidate brain function. The solution arrived at by the DFWG will not be imposed on the research community, but several groups that develop fMRI-related software have already indicated their willingness to adopt the solution. Suggestions for membership on the DFWG were broadly solicited from the research community.

The DFWG members are:

  • Chair: Stephen C. Strother (Veterans Affairs Medical Center, Minneapolis, Minnesota)
  • John Ashburner (Functional Imaging Laboratory, London, United Kingdom)
  • Hester Breman (Brain Innovation B.V., Maastricht, The Netherlands)
  • Robert W. Cox (National Institute of Mental Health, NIH, DHHS, Bethesda, Maryland)
  • Kate Fissell (University of Pittsburgh, Pittsburgh, Pennsylvania)
  • Christian Haselgrove (Massachusetts General Hospital, Charlestown, Massachusetts)
  • Colin J. Holmes (Silicon Graphics, Inc., Mountain View, California)
  • Peter Kochunov (University of Texas Health Science Center, San Antonio, Texas)
  • David E. Rex (University of California, Los Angeles)
  • Stephen M. Smith (Oxford University Centre for Functional MRI of the Brain, United Kingdom)
  • Jeffrey B. Woodward (Dartmouth College, Hanover, New Hampshire).
  • ex officio: Michael F. Huerta (National Institute of Mental Health, NIH, DHHS)
  • ex officio: Yuan Liu (National Institute of Neurological Disorders and Stroke, NIH, DHHS)

It should be noted that in no way is the NIfTI-1 format an official format whose use is mandated by the NIH. This effort has been made to help developers and users of functional neuroimaging software. What use is made of the format is now up to the community.

Q2. Why didn't the committee choose the DICOM format? The MINC-2 format? (Steve Strother)

DICOM: The DICOM standard attempts to address the extremely general requirements of digital imaging in diagnostic and therapeutic healthcare environments (http://medical.nema.org/dicom/), while the DFWG has a much narrower focus. The DFWG committee's strategy has been to adopt a two-pronged approach to developing a technical solution to the problem of multiple fMRI data formats by initially focusing on a relatively simple format that has low storage overhead, resolves some immediate format problems in the fMRI community and is not difficult for developers to learn and use. The NIfTI-1 format specification represents the simple first prong of this approach with the goal of consolidating the variants of the ANALYZE 7.5 format currently being used by the major fMRI software packages while staying mostly ANALYZE 7.5 compatible and explicitly dealing with the specification and storage of a data coordinate system.

The committee felt that DICOM did not satisfy the general requirements of a simple format for the fMRI community with DICOM's large, clinically focused storage overhead and the relatively complex specifications for multiframe MRI and spatial registration. In addition, the DICOM specification is also heavily concerned with data communication, something the committee felt was well beyond the scope of NIfTI-1.

MINC-2: The DFWG committee is very aware of the latest MINC developments through Colin Holmes' able and enthusiastic advocacy of MINC to the committee. MINC is being actively and seriously considered as a candidate for a NIfTI-2 format specification (see below). In addition, we have been provided with MINC 1.0 namespace (7/5/2003) and MINC 2.0 file format (11/18/2003) documents by Robert Vincent in Montreal. Most of the DFWG committee meet with Alan Evans, John Sled, Robert Vincent and several others to discuss MINC and its proposed developments at the last OHBM meeting in New York.

NIfTI-2: The second prong of the committee's approach (NIfTI-2) will be a more complex format specification to address the problem of comprehensive data interchange within the fMRI research community. Development of NIfTI-2 and inclusion of specifications for such data as nonlinear registrations, surfaces and various types of metadata (e.g., data analysis design matrices) are under discussion by the committee.

Q3. Can you add my favorite variable X to the header? (Jeff Woodward)

[Temporary answer by RW Cox]
Not very likely. We stayed within the restriction of a 348 byte header to keep compatibility with ANALYZE 7.5. Most of the space is now taken by new fields, agreed upon by the DFWG committee after extensive wrangling.

Q4. What is the minimum set of fields required to create a NIfTI-1 header? (Christian Haselgrove)

While not all of the NIfTI-1 header fields are necessary to describe a volume, most fields require a specific value to indicate the field's non-use.

Required fields are:

    FIELD         NOTES
    -----------------------------------------------------
    sizeof_hdr    must be 348
    -----------------------------------------------------
    dim           dim[0] and dim[1] are always required;
                  dim[2] is required for 2-D volumes,
                  dim[3] for 3-D volumes, etc.
    -----------------------------------------------------
    datatype      needed to specify type of image data
    -----------------------------------------------------
    bitpix        should correspond correctly to datatype
    -----------------------------------------------------
    pixdim        with the exception of pixdim[0] (which
                  is required when qform_code != 0),
                  pixdim[n] is required when dim[n] is
                  required
    -----------------------------------------------------
    vox_offset    required for an "n+1" header
    -----------------------------------------------------
    magic         must be "ni1\0" or "n+1\0"
    -----------------------------------------------------
The descrip and aux_file fields are not required. The NIfTI-1 standard does not specify any use or interpretation of these fields.

The remaining fields are not required, but their non-use must be indicated as in the following table. The simplest way to ensure this when creating a 348-byte header structure is to fill it with zeros (e.g., with calloc()) before setting any desired fields to their appropriate values.

    FIELD           NON-USE INDICATOR
    ---------------------------------------------------
    intent_code    intent_code = NIFTI_INTENT_NONE = 0
    intent_name    and intent_name[0] = '\0'
    intent_p1
    intent_p2
    intent_p3
    ---------------------------------------------------
    scl_slope      scl_slope = 0
    scl_inter
    ---------------------------------------------------
    xyzt_units     xyzt_units = NIFTI_UNITS_UNKNOWN = 0
    ---------------------------------------------------
    cal_max        cal_max = 0 and cal_min = 0
    cal_min
    ---------------------------------------------------
    toffset        toffset = 0
    ---------------------------------------------------
    slice_code     slice_code = 0 and dim_info = 0
    dim_info
    slice_start
    slice_end
    slice_duration
    ---------------------------------------------------
    qform_code     qform_code = 0 (see note below)
    quatern_b
    quatern_c
    quatern_d
    qoffset_x
    qoffset_y
    qoffset_z
    pixdim[0]
    ---------------------------------------------------
    sform_code     sform_code = 0
    srow_x
    srow_y
    srow_z
    ---------------------------------------------------
N.B.: Using qform_code=0 is legal, but not recommended. This case is intended for the case when you don't want to encode any orientation information in the header. It is mainly intended for compatibility with older ANALYZE 7.5 files; however, the ANALYZE 7.5 orient field is not contained in a NIfTI-1 header. If qform_code=0, a program may treat the orientation of a NIfTI-1 file in any way; this is unlikely to be portable or inter-operable.

Q5. What format converters are available? (David Rex)

Q6. What I/O libraries are available? (Kate Fissell)

A C/C++ I/O library for NIfTI-1 is available at http://nifti.nimh.nih.gov/dfwg/src :

  • nifti1.h -- The header file for the NIfTI-1 format.
  • nifti1_io.c -- The I/O functions for the NIfTI-1 format.
  • nifti1_io.h -- The header file for the I/O functions for the NIfTI-1 format.
  • nifti1_test.c -- A short sample program to read and write NIfTI-1 files.
These files were contributed by Robert Cox, NIH, and contain functions to read and write NIfTI-1 headers and data blocks, print header fields, and, functions to manipulate some of the more complicated data items in the NIfTI-1 header (e.g., transform matrices).

We expect that I/O libraries in MATLAB and Java will be available in the not too distant future. Any and all contributed libraries are welcome.

Q7. How do I tell if an ANALYZE header is NIfTI-1 compatible? (Christian Haselgrove)

NIfTI-1 headers must contain a specific sequence of bytes in the last four bytes of the header (bytes 344-348):

  • When there is a separate file for the image data, these bytes must be "ni1\0" (hexadecimal 6e 69 31 00).
  • When the image data is in the same file as the header, these bytes must be "n+1\0" (hexadecimal 6e 2b 31 00).

If neither of these conditions is satisfied, then a program should not presume that the NIfTI-1 additions/changes to the ANALYZE format are present in the header.

Q8. Is NIfTI-1 compatible with the ANALYZE 7.5 file format? (Jeff Woodward)

[Temporary answer by RW Cox]
We hope so. The interpretation of many of the fields in the ANALYZE 7.5 header is not very clear. Most such fields aren't widely used by software other than ANALYZE itself. After considerable discussion, we kept the ANALYZE 7.5-defined fields that seemed widely used in the FMRI community. The goal was to have non-NIfTI-aware FMRI packages that use the ANALYZE 7.5 format still be able to read most NIfTI-1 files. Time and experience will tell if this goal has been met.

Q9. Do I need to convert all of my files to this format? (Colin Holmes)

No. NIfTI-1 was created to provide a common and widely acceptable version of the ANALYZE-7.5 format that could act as an image data interchange format between neuroimaging programs and analysis packages. As it provides little support for storage of required metadata (e.g., image acquisition parameters), it is not a complete solution for long-term archiving of neuroimaging data. For this function, please see the NIfTI-2 format (coming soon to a lab near you).

Q10. Is the NIfTI-1 header extensible? (Hester Breman)

The NIfTI-1 files can exist in two forms. There can be a single *.nii file or two separate files, a *.hdr and a *.img file (see the NIfTI-1 header file for more details).

When the information is separated into a *.hdr and *.img file, which resembles the original ANALYZE 7.5 format, any programs that read the ANALYZE format will expect a header of 348 bytes. Therefore the NIfTI-1 header is not extensible in this form, since any program is likely to fail when it detects that the header file is not the expected size.

While it is possible to store data between the header and the image part of a single *.nii file, this is non-standard and no other program will will be able to interpret these data. Therefore it is not recommended to produce such files.

In the current NIfTI-1 format, there are many possibilities to store different kinds of data in the image part of the file. Datasets, many types of statistical values, vectors, meshes, etc., all can be stored in NIfTI-1. Each NIfTI-1-aware program will be able to read these files. Interpretation of the files will also be possible, since the meaning of the fields is determined, when the intent of the file is known.

For any other types of data that cannot be stored in the NIfTI-1 format, eventually a NIfTI-2 format for complex data is to come.

Q11. What modalities does this format support? (Colin Holmes)

NIfTI-1 can store image data from any modality such as PET, MRI, CT, EEG that produces regularly sampled 1-5D rasters. No support is provided for modality-specific metadata such as dose, pulse sequence or indeed the majority of subject oriented descriptive items.

A limited amount of information specific to FMRI time series acquisition is available in the NIfTI-1 header:

  • Marking the frequency, phase, and slice encoding directions.
  • Storing the per-slice acquisition time.
  • Storing the slice acquisition order (e.g., interleaving).
This particular information is present since the primary thrust of the DFWG has been to make FMRI data analysis software inter-operable.

Q12. What types of data can I store in the format? (Colin Holmes)

NIfTI-1 provides support for regularly sampled raster-oriented data of up to five dimensions (e.g., image data). The data type of each value stored in the raster grid must be the same, and is indicated in the datatype header field. These data types are intended to encompass a wide range of commonly usages. Expressed in C language syntax, these basic data types are:

   unsigned char          = 8-bit byte     [     0..  255]
   signed char             = 8-bit byte     [  -128..  127]
   signed short            = 16-bit integer [-32768..32767]
   unsigned short         = 16-bit integer [     0..65535]
   signed int                = 32-bit integer
   unsigned int             = 32-bit integer
   signed long long       = 64-bit integer
   unsigned long long    = 64-bit integer
   float                         = 32-bit floating point value
   double                     = 64-bit floating point value
   long double              = 128-bit floating point value
   { float r,i ; }               = 64-bit complex = 2 32-bit floats
   { double r,i ; }            = 128-bit complex = 2 64-bit floats
   {long double r,i;}        = 256-bit complex = 2 128-bit floats
   {unsigned char r,g,b;} = RGB triple = 3 8-bit bytes
Not all data types will be supported by all programs; in fact, most programs will probably only operate on a limited set of these data types. A well-crafted NIfTI-1 compatible program should detect when it cannot deal with an input file's data type, and exit gracefully.

The first 3 dimensions are reserved for space; the fourth dimension for time (or frequency); the fifth dimension is intended to allow storing multiple values at each spatio-temporal location. In addition, the intent_code field can be used to describe if and how the fifth dimension of the image data is organized. Possible organizations include vector, general matrix, symmetric matrix, and quaternion.

NIfTI-1 does not provide for the storage of data sets defined over irregularly sampled domains, such as cortical surface models. Nor does NIfTI-1 provide for storage of the definitions of such domains.

Q13. Does NIfTI-1 solve the problem of data interchange in fMRI? (Colin Holmes)

Yes and no. NIfTI-1 can act as a conduit for image data (only) being exchanged between programs in an analysis sequence. It does not provide for the long-term and complete storage of image and metadata and associated computed results (e.g., surfaces) that is necessary to provide for the complete and robust preservation of data for historical, archival or full-fledged interlaboratory exchange of neuroimaging data.

Q14. What is the default orientation? (John Ashburner)

The NIfTI format allows storage on disk to be in either a left- or right-handed coordinate system. However, the format includes an implicit spatial transformation into a RIGHT-HANDED coordinate system. This transform maps from data coordinates (e.g. column i, row j, slice k), into some real world (x,y,z) positions in space. These positions could relate to Talairach-Tournoux (T&T) space, MNI space, or patient-based scanner coordinates.

For T&T, and MNI coordinates, x increases from left to right, y increases from posterior to anterior, and z increases in the inferior to superior direction. Directions in the scanner coordinate system are similar. MRI data is usually exported as DICOM format, which encodes the positions and orientations of the slices. When data are converted from DICOM to NIfTI-1 format, the relevant information can be determined from the Pixel Spacing, Image Orientation (Patient) and Image Position (Patient) fields of the DICOM files.

NIfTI-1 also allows the space of one image to be mapped to that of another (via a rigid or affine transform). This is to enable on-the-fly resampling of registered images. This would allow intra-subject images, collected with lots of different orientations or resolutions, to be treated as if they are all in register.

Q15. Is the default radiological or neurological orientation? (John Ashburner)

Neurological and radiological conventions only relate to visualization of axial images. They are unrelated to how the data are stored on disk, or even how the real-world coordinates are represented.

It is more appropriate to consider whether the real-world coordinate system is left- or right-handed (see below). Talairach and Tournoux use a right-handed system, whereas the storage convention of ANALYZE files is usually considered as left-handed. These coordinate systems are mirror images of each other (if you are a psychologist, try explaining why mirror images appear to be left-right flipped, rather than flipped up-down, or back-front). Transforming between left- and right-handed coordinate systems involves flipping, and can not be done by rotations alone.

Q16. What is a quaternion? (Bob Cox)

A quaternion is a mathematical object that contains 4 real numbers. Historically, quaternions were discovered* by William Rowan Hamilton in 1843. This antedates the discovery of vectors and matrices, which are more widely taught in modern times.

Like real and complex numbers, quaternions can be added and multiplied. Unlike real and complex numbers, the order in which quaternions are multiplied makes a difference. In Hamilton's notation, which is still used, a quaternion is represented as the sum of 4 real numbers times the basis symbols 1, i, j, and k; for example:

   q = a 1 + b i + c j + d k
p = u 1 + v i + w j + x k
Quaternions are added component by component. Multiplication is done via the following rules:

  1 * X =  X   [for any X]
i * j =  k
j * i = -k   [anti-commutative]
j * k =  i
k * j = -i   [anti-commutative]
k * i =  j
i * k = -j   [anti-commutative]
i * i = -1   [each of i, j, and k   ]
j * j = -1   [is a square root of -1]
k * k = -1
So the example quaternions above multiply out to

  q*p = (a*u-b*v-c*w-d*x) 1 + (a*v+b*u+c*x-d*w) i
       +(a*w-b*x+c*u+d*v) j + (a*x+b*w-c*v+d*u) k
A principal application of quaternions is to represent 3D rotations. How this is done is described in great detail in the NIfTI-1 C header, and also here. The reason this representation is used in NIfTI-1 is to save space in the 348-byte header; a quaternion only requires 4 floats (16 bytes) to specify, but a 3x3 matrix requires 9 floats (36 bytes). The nifti1_io.c I/O library contains functions to convert quaternions to rotation matrices, and vice-versa.

*I am a strict Platonic Idealist in these matters.

Q17. What alignment information is stored in the NIfTI-1 header? (Christian Haselgrove)

Volume orientation is given by a transformation that maps voxel indices (i,j,k) to spatial coordinates (x,y,z), typically anatomical coordinates assigned by the scanner. This transformation ("Method 2" in the nifti1.h documentation) is generated using the voxel dimensions, a quaternion encoding a rotation matrix, and a 3D shift, all stored in the NIfTI-1 header; details can be found in the nifti1.h comments.

The NIfTI-1 header also provides for a general affine transformation, separate from that described by Method 2. This transformation ("Method 3") also maps voxel indices (i,j,k) to (x,y,z), which in this case are typically coordinates in a standard space such as the Talairach space. The elements of this transformation matrix are stored in the NIfTI-1 header. For example, the Method 2 transformation can be constructed from the attributes from a set of DICOM files; the Method 3 transform can be computed offline and inserted into the header later.

The exact "meaning" of the coordinates given by the Method 2 and Method 3 transformations is recorded in header fields qform_code and sform_code, respectively. Code values can indicate if the (x,y,z) axes are

  • Anatomical coordinates from the scanner (e.g., the DICOM header)
  • Aligned to some anatomical "truth" or standard
  • Aligned and warped to Talairach-Tournoux coordinates
  • Aligned and warped to MNI-152 coordinates

 It is possible that neither transformation is specified (i.e., qform_code=sform_code=0), in which case we are left with the voxel size in pixdim[], and no orientation is given or assumed. This use ("Method 1") is discouraged.

Q18. Does NIfTI-1 support a single file format for header and data? (Bob Cox)

Yes. In this format, the 348 byte header comes first in the file. The image data follows. The image data offset in the file is specified by the vox_offset field in the header. Note that the magic field for a single file is "n+1", whereas that for a double file is "ni1". This means that it is the contents of the header that determines if the data is stored in the same file as the header or a different file. The filename itself (*.hdr or *.nii) does not necessarily specify the double or single storage format.

In principle, one could put arbitrary information between the header and the image data, by making vox_offset be larger than 348. This is not recommended. Such a file would not be compatible or portable, which is the entire point of the NIfTI-1 effort.

We recommend the use of the suffix .nii for a single header+data NIfTI-1 format file. This suffix does not have any previous meaning attached, unlike the more obvious .nif (Navy Image File). For more information on connotations of various suffixes that start with "n", see http://www.icdatamaster.com/n.html.

Created by aclark
Last modified 2004-09-21 06:40 PM


The NIfTI-1 header

The NIfTI-1 header has the following entries (see below). The size should be indicated as 348, to keep compatibility with Analyze 7.5 reader software. Although the header size field should indicate '348', the real size of the nifti-1 header is 352 bytes.

datatype fieldname

NIFTI-1 usage

ANALYZE 7.5 field(s)

was header_key substruct

int sizeof_hdr

MUST be 348

int sizeof_hdr

char data_type[10]

Unused

char data_type[10]

char db_name[18]

Unused

char db_name[18]

int extents

Unused

int extents

short session_error

Unused

short session_error

char regular

Unused

char regular

char dim_info

MRI slice ordering

char hkey_un0

was image_dimension substruct

short dim[0]

Data array dimensions; dim[0] = number of dimensions; if dim[0] is outside range 1..7, then the header information needs to be byte swapped appropriately

short dim[8]

short dim[1]

NIFTI-1 reserves dimensions 1,2,3 for space x,y,z

short dim[2]

short dim[3]

short dim[4]

NIFTI-1 reserves dimensions 4 for time (t)

short dim[5]

storing multiple values at each spatiotemporal voxel

short dim[6]

short dim[7]

float intent_p1

1st intent parameter

short unused8, short unused9

float intent_p2

2nd intent parameter

short unused10, short unused11

float intent_p3

3rd intent parameter

short unused12, short unused13

short intent_code

NIFTI_INTENT_* code

short unused14

short datatype

Defines data type

short datatype

short bitpix

Number bits/voxel

short bitpix

short slice_start

First slice index

short dim_un0

float pixdim[0]

Grid spacings; Method 2 uses a factor 'qfac' which is either -1 or 1; qfac is stored in the otherwise unused pixdim[0]. If pixdim[0]=0.0 (which should not occur), we take qfac=1

float pixdim[8]

float pixdim[1]

x scale

float pixdim[2]

y scale

float pixdim[3]

z scale

float pixdim[4]

float pixdim[5]

float pixdim[6]

float pixdim[7]

float vox_offset

Offset into .nii file (should be at least 352)

float vox_offset

float scl_slope

Data scaling: slope

float funused1

float scl_inter

Data scaling: offset

float funused2

short slice_end

Last slice index

float funused3

char slice_code

Slice timing order

float funused3

char xyzt_units

dx, dy, dz & dt units: NIFTI_UNITS_* code

float funused3

float cal_max

Max display intensity

float cal_max

float cal_min

Min display intensity

float cal_min

float slice_duration

Time for 1 slice

float compressed

float toffset

Time axis shift

float verified

int glmax

Unused

int glmax

int glmin

Unused

int glmin

was data_history substruct

char descrip[80]

char descrip[80]

char aux_file[24]

auxiliary filename

char aux_file[24]

short qform_code

NIFTI_XFORM_* code

all ANALYZE 7.5 fields below here are replaced

short sform_code

sform_code > 0 indicates affine transformation

float quatern_b

Quaternion b param

float quatern_c

Quaternion c param

float quatern_d

Quaternion d param

float qoffset_x

Quaternion x shift

float qoffset_y

Quaternion y shift

float qoffset_z

Quaternion z shift

float srow_x[4]

1st row affine transform

float srow_y[4]

2nd row affine transform

float srow_z[4]

3rd row affine transform

char intent_name[16]

'name' or meaning of data

char magic[4]

Indicates nifti-type; must be "ni1\0" or "n+1\0"

byte extension[4]

extension = (esize/16) + (222 *code)


Extending the data in a NIfTI-1 header

Robert W Cox — SSCC/DIRP/NIMH/NIH/DHHS/USA/Earth — 07 October 2004

Clarifying vox_offset

float vox_offset ;

In a .nii file, the vox_offset field value is interpreted as the start location of the image data bytes in that file. In a .hdr/.img file pair, the vox_offset field value is the start location of the image data bytes in the .img file.

  • If vox_offset is less than 352 in a .nii file, it is equivalent to 352 (i.e., image data never starts before byte #352 in a .nii file).
  • The default value for vox_offset in a .nii file is 352; in a .hdr file it is 0.
  • vox_offset should be an integer multiple of 16; otherwise, some programs may not work properly (e.g., SPM). This is to allow memory-mapped input to be properly byte-aligned.

Note that since vox_offset is an IEEE-754 32 bit float (for compatibility with the ANALYZE-7.5 format), it effectively has a 24 bit mantissa. All integers from 0 to 224 can be represented exactly in this format, but not all larger integers are exactly storable as IEEE-754 32 bit floats. However, unless you plan to have vox_offset be potentially larger than 16 MB, this should not be an issue. (Actually, any integral multiple of 16 up to 227 can be represented exactly in this format, which allows for up to 128 MB of random information before the image data.)

In a .img file (i.e., image data stored separately from the NIfTI-1 header), data bytes between #0 and #vox_offset-1 (inclusive) are completely undefined and unregulated by the NIfTI-1 standard. One potential use of having vox_offset > 0 in the .hdr/.img file pair storage method is to make the .img file be a copy of (or link to) a pre-existing image file in some other format, such as DICOM; then vox_offset would be set to the offset of the image data in this file. (It may not be possible to follow the “multiple-of-16 rule” with an arbitrary external file; using the NIfTI-1 format in such a case may lead to a file that is incompatible with software that relies on vox_offset being a multiple of 16.)

In a .nii file, data bytes between #348 and #vox_offset-1 (inclusive) may be used to store user-defined extra information; similarly, in a .hdr file, any data bytes after byte #347 are available for user-defined extra information. The (very weak) regulation of this extra header data is described next.

Extended Header Data Section(s)

byte extension[4] ;

After the end of the 348 byte header (e.g., after the magic field), the next 4 bytes are an byte array field named "extension". By default, all 4 bytes of this array should be set to zero. In a .nii file, these 4 bytes will always be present, since the earliest start point for the image data is byte #352. In a separate .hdr file, these bytes may or may not be present. If not present (i.e., if the length of the .hdr file is 348 bytes), then a NIfTI-1 compliant program should use the default value of extension={0,0,0,0}. The first byte (extension[0]) is the only value of this array that is specified at present. The other 3 bytes are reserved for future use.

If extension[0] is nonzero, it indicates that extended header information is present in the bytes following the extension array. In a .nii file, this extended header data is before the image data (and vox_offset must be set correctly to allow for this). In a .hdr file, this extended data follows extension and proceeds (potentially) to the end of the file.

The format of extended header data is weakly specified. Each extension must be an integer multiple of 16 bytes long. The first 8 bytes of each extension comprise 2 integers:

int esize , ecode ;

These values may need to be byte-swapped, as indicated by dim[0]for the rest of the header.

  • esize is the number of bytes that form the extended header data

¨ esize must be a positive integral multiple of 16

¨ this length includes the 8 bytes of esize and ecode themselves

  • ecode is a non-negative integer that indicates the format of the extended header data that follows

¨ different ecode values are assigned to different developer groups

¨ at present, the “registered” values for code are

o 0 = unknown private format (not recommended!)

o 2 = DICOM format (i.e., attribute tags and values)

o 4 = AFNI group (i.e., ASCII XML-ish elements)

In the interests of interoperability (a primary rationale for NIfTI), groups developing software that uses this extension mechanism are encouraged to document and publicize the format of their extensions. To this end, the NIfTI DFWG will assign even numbered codes upon request to groups submitting at least rudimentary documentation for the format of their extension; at present, the contact is rwcox@nih.gov. The assigned codes and documentation will be posted on the NIfTI website. All odd values of ecode (and 0) will remain unassigned; at least, until the even ones are used up, when we get to 2,147,483,646.

Note that the other contents of the extended header data section are totally unspecified by the NIfTI-1 standard. In particular, if binary data is stored in such a section, its byte order is not necessarily the same as that given by examining dim[0]; it is incumbent on the programs dealing with such data to determine the byte order of binary extended header data.

Multiple extended header sections are allowed, each starting with an esize,ecode value pair. The first esize value, as described above, is at bytes #352-355 in the .hdr or .nii file (files start at byte #0). If this value is positive, then the second (esize2) will be found starting at byte #352+esize 1 , the third (esize3) at byte #352+esize1+ esize2 , et cetera. Of course, in a .nii file, the value of vox_offset must be compatible with these extensions. If a malformed file indicates that an extended header data section would run past vox_offset, then the entire extended header section should be ignored. In a .hdr file, if an extended header data section would run past the end-of-file, that extended header data should also be ignored.

With the above scheme, a program can successively examine the esize and ecode values, and skip over each extended header section if the program doesn’t know how to interpret the data within. Of course, any program can simply ignore all extended header sections simply by jumping straight to the image data using vox_offset.


Data dimensionality

Vector-valued datasets

Data storage

Files

Byte ordering

Data scaling

Types of data

Unused fields

(as in ANALYZE 7.5):

dim[0] = number of dimensions;

- if dim[0] is outside range 1..7, then the header information needs to be byte swapped appropriately

- ANALYZE supports dim[0] up to 7, but NIFTI-1 reserves dimensions 1,2,3 for space (x,y,z), 4 for time (t), and 5,6,7 for anything else needed.

dim[i] = length of dimension #i, for i=1..dim[0] (must be positive)

- also see the discussion of intent_code, far below

pixdim[i] = voxel width along dimension #i, i=1..dim[0] (positive)

- cf. ORIENTATION section below for use of pixdim[0]

- the units of pixdim can be specified with the xyzt_units

field (also described far below).

Number of bits per voxel value is in bitpix, which MUST correspond with the datatype field. The total number of bytes in the image data is

dim[1] * ... * dim[dim[0]] * bitpix / 8

In NIFTI-1 files, dimensions 1,2,3 are for space, dimension 4 is for time, and dimension 5 is for storing multiple values at each spatiotemporal voxel. Some examples:

- A typical whole-brain FMRI experiment's time series:

- dim[0] = 4

- dim[1] = 64 pixdim[1] = 3.75 xyzt_units = NIFTI_UNITS_MM | NIFTI_UNITS_SEC

- dim[2] = 64 pixdim[2] = 3.75

- dim[3] = 20 pixdim[3] = 5.0

- dim[4] = 120 pixdim[4] = 2.0

- A typical T1-weighted anatomical volume:

- dim[0] = 3

- dim[1] = 256 pixdim[1] = 1.0 xyzt_units = NIFTI_UNITS_MM

- dim[2] = 256 pixdim[2] = 1.0

- dim[3] = 128 pixdim[3] = 1.1

- A single slice EPI time series:

- dim[0] = 4

- dim[1] = 64 pixdim[1] = 3.75 xyzt_units = NIFTI_UNITS_MM | NIFTI_UNITS_SEC

- dim[2] = 64 pixdim[2] = 3.75

- dim[3] = 1 pixdim[3] = 5.0

- dim[4] = 1200 pixdim[4] = 0.2

- A 3-vector stored at each point in a 3D volume:

- dim[0] = 5

- dim[1] = 256 pixdim[1] = 1.0 xyzt_units = NIFTI_UNITS_MM

- dim[2] = 256 pixdim[2] = 1.0

- dim[3] = 128 pixdim[3] = 1.1

- dim[4] = 1 pixdim[4] = 0.0

- dim[5] = 3 intent_code = NIFTI_INTENT_VECTOR

- A single time series with a 3x3 matrix at each point:

- dim[0] = 5

- dim[1] = 1 xyzt_units = NIFTI_UNITS_SEC

- dim[2] = 1

- dim[3] = 1

- dim[4] = 1200 pixdim[4] = 0.2

- dim[5] = 9 intent_code = NIFTI_INTENT_GENMATRIX

- intent_p1 = intent_p2 = 3.0 (indicates matrix dimensions)

VECTOR-VALUED DATASETS

The 5th dimension of the dataset, if present (i.e., dim[0]=5 and dim[5] > 1), contains multiple values (e.g., a vector) to be stored

at each spatiotemporal location. For example, the header values

- dim[0] = 5

- dim[1] = 64

- dim[2] = 64

- dim[3] = 20

- dim[4] = 1 (indicates no time axis)

- dim[5] = 3

- datatype = DT_FLOAT

- intent_code = NIFTI_INTENT_VECTOR

mean that this dataset should be interpreted as a 3D volume (64x64x20), with a 3-vector of floats defined at each point in the 3D grid.

A program reading a dataset with a 5th dimension may want to reformat the image data to store each voxels' set of values together in a struct or array. This programming detail, however, is beyond the scope of the NIFTI-1 file specification! Uses of dimensions 6 and 7 are also not specified here.

DATA STORAGE

If the magic field is "n+1", then the voxel data is stored in the same file as the header. In this case, the voxel data starts at offset

(int)vox_offset into the header file. Thus, vox_offset=348.0 means that the data starts immediately after the NIFTI-1 header. If vox_offset is

greater than 348, the NIFTI-1 format does not say anything about the contents of the dataset file between the end of the header and the start of the data.

FILES

If the magic field is "ni1", then the voxel data is stored in the associated ".img" file, starting at offset 0 (i.e., vox_offset is not

used in this case, and should be set to 0.0).

When storing NIFTI-1 datasets in pairs of files, it is customary to name the files in the pattern "name.hdr" and "name.img", as in ANALYZE 7.5.

When storing in a single file ("n+1"), the file name should be in the form "name.nii" (the ".nft" and ".nif" suffixes are already taken;

cf. http://www.icdatamaster.com/n.html ).

BYTE ORDERING

The byte order of the data arrays is presumed to be the same as the byte order of the header (which is determined by examining dim[0]). Floating point types are presumed to be stored in IEEE-754 format.

DATA SCALING

If the scl_slope field is nonzero, then each voxel value in the dataset should be scaled as y = scl_slope * x + scl_inter

where x = voxel value stored y = "true" voxel value

Normally, we would expect this scaling to be used to store "true" floating values in a smaller integer datatype, but that is not required. That is,

it is legal to use scaling even if the datatype is a float type (crazy, perhaps, but legal).

- However, the scaling is to be ignored if datatype is DT_RGB24.

- If datatype is a complex type, then the scaling is to be applied to both the real and imaginary parts.

The cal_min and cal_max fields (if nonzero) are used for mapping (possibly scaled) dataset values to display colors:

- Minimum display intensity (black) corresponds to dataset value cal_min.

- Maximum display intensity (white) corresponds to dataset value cal_max.

- Dataset values below cal_min should display as black also, and values

above cal_max as white.

- Colors "black" and "white", of course, may refer to any scalar display

scheme (e.g., a color lookup table specified via aux_file).

- cal_min and cal_max only make sense when applied to scalar-valued datasets (i.e., dim[0] < 5 or dim[5] = 1).

TYPE OF DATA (acceptable values for datatype field)

Values of datatype smaller than 256 are ANALYZE 7.5 compatible. Larger values are NIFTI-1 additions. These are all multiples of 256, so that no bits below position 8 are set in datatype. But there is no need to use only powers-of-2, as the original ANALYZE 7.5 datatype codes do.

The additional codes are intended to include a complete list of basic scalar types, including signed and unsigned integers from 8 to 64 bits, floats from 32 to 128 bits, and complex (float pairs) from 64 to 256 bits.

Note that most programs will support only a few of these datatypes! A NIFTI-1 program should fail gracefully (e.g., print a warning message) when it encounters a dataset with a type it doesn't like.

UNUSED FIELDS

Some of the ANALYZE 7.5 fields marked as ++UNUSED++ may need to be set to particular values for compatibility with other programs. The issue of interoperability of ANALYZE 7.5 files is a murky one -- not all programs require exactly the same set of fields. (Unobscuring this murkiness is a principal motivation behind NIFTI-1.)

Some of the fields that may need to be set for other (non-NIFTI aware) software to be happy are:

extents dbh.h says this should be 16384

regular dbh.h says this should be the character 'r'

glmin, glmax dbh.h says these values should be the min and max voxel values for the entire dataset

It is best to initialize ALL fields in the NIFTI-1 header to 0 (e.g., with calloc()), then fill in what is needed.

Information from nifti1.h by RW Cox, NIH

Top


Statistics and NIfTI

NIfTI-1 Statistical parametrical data

NIfTI-1 Statistical distributions

Statistics in NIfTI-1 chart

STATISTICAL PARAMETRIC DATASETS (i.e., SPMs):

Values of intent_code from NIFTI_FIRST_STATCODE to NIFTI_LAST_STATCODE (inclusive) indicate that the numbers in the dataset should be interpreted

as being drawn from a given distribution. Most such distributions have auxiliary parameters (e.g., NIFTI_INTENT_TTEST has 1 DOF parameter).

If the dataset DOES NOT have a 5th dimension, then the auxiliary parameters are the same for each voxel, and are given in header fields intent_p1, intent_p2, and intent_p3.

If the dataset DOES have a 5th dimension, then the auxiliary parameters are different for each voxel. For example, the header values

- dim[0] = 5

- dim[1] = 128

- dim[2] = 128

- dim[3] = 1 (indicates a single slice)

- dim[4] = 1 (indicates no time axis)

- dim[5] = 2

- datatype = DT_FLOAT

- intent_code = NIFTI_INTENT_TTEST

mean that this is a 2D dataset (128x128) of t-statistics, with the t-statistic being in the first "plane" of data and the degrees-of-freedom parameter being in the second "plane" of data.

If the dataset 5th dimension is used to store the voxel-wise statistical parameters, then dim[5] must be 1 plus the number of parameters required by that distribution (e.g., intent_code=NIFTI_INTENT_TTEST implies dim[5] must be 2, as in the example just above).

Note: intent_code values 2..10 are compatible with AFNI 1.5x (which is why there is no code with value=1, which is obsolescent in AFNI).

Information from nifti1.h by RW Cox, NIH


Statistical data

page 2


Statistical Distributions 2

page 3


Statistical Distributions 3

page 4


Statistical Distributions 4

page 5


Statistical Distributions 5

page 6


Statistical Distributions 6

page 7


Statistical Distributions 7

page 8


Statistical Distributions 8

To Statistical Distributions 1 Main index


Other data

Other data intentions

Other data intensions chart

Intent codes for other intentions

The purpose of the intent_* fields is to help interpret the values stored in the dataset. Some non-statistical values for intent_code and conventions are provided for storing other complex data types.

The intent_name field provides space for a 15 character (plus 0 byte) 'name' string for the type of data stored. Examples:

- intent_code = NIFTI_INTENT_ESTIMATE; intent_name = "T1"; could be used to signify that the voxel values are estimates of the NMR parameter T1.

- intent_code = NIFTI_INTENT_TTEST; intent_name = "House"; could be used to signify that the voxel values are t-statistics for the significance of 'activation' response to a House stimulus.

- intent_code = NIFTI_INTENT_DISPVECT; intent_name = "ToMNI152"; could be used to signify that the voxel values are a displacement vector that transforms each voxel (x,y,z) location to the corresponding location in the MNI152 standard brain.

- intent_code = NIFTI_INTENT_SYMMATRIX; intent_name = "DTI"; could be used to signify that the voxel values comprise a diffusion tensor image.

Information from nifti1.h by RW Cox, NIH


Transformations

Data conversion

At least the following checks and conversions need to be performed in case of reading c.q. converting a NIfTI-1 file correctly.

These conversions are performed automatically when using the *nifti_image_read( char *hname , int read_data ) method as provided by R.W. Cox in the nifti1_io.c code.

General

1. Check filetype: single file (*.nii) or dual (*.hdr/*.img): use int is_nifti_file( char *hname ) in nifti1_io

Data sets

1. Convert to world coordinates

2. Compute or extract quaternion

3. Compute or extract slice acquisition and timing parameters

4. Swap bytes in case of incongruent endianness

5. Check for extensions


Intensity values

Data conversion

This page provides a summary of the available NIfTI-1 data conversion and extraction methods in nifti1.h and nifti1_io.h/c.

1. Convert to world coordinates

Method 1: translation only: use pixdim[1,2,3] parameters

Method 2: rigid body transformation: use pixdim[1,2,3], quaternion parameters and offset parameter

Method 3: affine transformation: use matrix in srow_x,y,z parameters

Available function in nifti1_io for methods 2 and 3: mat44_to_orientation( )

2. Compute or extract quaternion

Use quatern_to_mat44( ) and mat44_to_quatern( ) in nifti1_io.

3. Compute or extract slice acquisition details and timing parameters

The nifti1 macro's DIM_INFO_TO_FREQ_DIM, DIM_INFO_TO_PHASE_DIM, and DIM_INFO_TO_SLICE_DIM can be used to extract the slice acquisition and timing parameter values from the dim_info byte. The macro FPS_INTO_DIM_INFO in nifti1 uses parameters in freq_dim, phase_dim and slice_dim.

The macros XYZT_TO_SPACE and XYZT_TO_TIME can be used to mask off the undesired bits from the xyzt_units fields, leaving "pure" space and time codes. Inversely, the macro SPACE_TIME_TO_XYZT can be used to assemble a space code (0,1,2,...,7) with a time code (0,8,16,32,...,56) into the combined value for xyzt_units.

4. Swap bytes in case of incongruent endianness

Use macro NIFTI_NEEDS_SWAP( ) in nifti1.h and
 methods swap_nifti_header( )
 and swap_2bytes( ), swap_4bytes(
 ), swap_8bytes( ), swap_16bytes(
 ) and swap_Nbytes( ) in
 nifti1_io.

5. Check for extensions

In case extra data are provided with the file, this is indicated in the bytes 348 - 352 of the NIfTI-1 header.


Conversion to world coordinates

3D IMAGE (VOLUME) ORIENTATION AND LOCATION IN SPACE

There are 3 different methods by which continuous coordinates can attached to voxels. The discussion below emphasizes 3D volumes, and

the continuous coordinates are referred to as (x,y,z). The voxel index coordinates (i.e., the array indexes) are referred to as (i,j,k),

with valid ranges:

i = 0 .. dim[1]-1

j = 0 .. dim[2]-1 (if dim[0] >= 2)

k = 0 .. dim[3]-1 (if dim[0] >= 3)

The (x,y,z) coordinates refer to the CENTER of a voxel. In methods 2 and 3, the (x,y,z) axes refer to a subject-based coordinate system,

with +x = Right +y = Anterior +z = Superior.

This is a right-handed coordinate system. However, the exact direction these axes point with respect to the subject depends on qform_code

(Method 2) and sform_code (Method 3).

N.B.: The i index varies most rapidly, j index next, k index slowest. Thus, voxel (i,j,k) is stored starting at location (i + j*dim[1] + k*dim[1]*dim[2]) * (bitpix/8) into the dataset array.

N.B.: The ANALYZE 7.5 coordinate system is +x = Left +y = Anterior +z = Superior which is a left-handed coordinate system. This backwardness is too difficult to tolerate, so this NIFTI-1 standard specifies the coordinate order which is most common in functional neuroimaging.

N.B.: The 3 methods below all give the locations of the voxel centers in the (x,y,z) coordinate system. In many cases, programs will wish to display image data on some other grid. In such a case, the program will need to convert its desired (x,y,z) values into (i,j,k) values in order to extract (or interpolate) the image data. This operation would be done with the inverse transformation to those described below.

N.B.: Method 2 uses a factor 'qfac' which is either -1 or 1; qfac is stored in the otherwise unused pixdim[0]. If pixdim[0]=0.0 (which should not occur), we take qfac=1. Of course, pixdim[0] is only used when reading a NIFTI-1 header, not when reading an ANALYZE 7.5 header.

N.B.: The units of (x,y,z) can be specified using the xyzt_units field.

METHOD 1 (the "old" way, used only when qform_code = 0):

The coordinate mapping from (i,j,k) to (x,y,z) is the ANALYZE 7.5 way. This is a simple scaling relationship:

x = pixdim[1] * i

y = pixdim[2] * j

z = pixdim[3] * k

No particular spatial orientation is attached to these (x,y,z) coordinates. (NIFTI-1 does not have the ANALYZE 7.5 orient field, which is not general and is often not set properly.) This method is not recommended, and is present mainly for compatibility with ANALYZE 7.5 files.

METHOD 2 (used when qform_code > 0, which should be the "normal case):

The (x,y,z) coordinates are given by the pixdim[] scales, a rotation matrix, and a shift. This method is intended to represent "scanner-anatomical" coordinates, which are often embedded in the image header (e.g., DICOM fields (0020,0032), (0020,0037), (0028,0030), and (0018,0050)), and represent the nominal orientation and location of the data. This method can also be used to represent "aligned" coordinates, which would typically result from some post-acquisition alignment of the volume to a standard orientation (e.g., the same subject on another day, or a rigid rotation to true anatomical orientation from the tilted position of the subject in the scanner). The formula for (x,y,z) in terms of header parameters and (i,j,k) is:

[ x ] [ R11 R12 R13 ] [ pixdim[1] * i ] [ qoffset_x ]

[ y ] = [ R21 R22 R23 ] [ pixdim[2] * j ] + [ qoffset_y ]

[ z ] [ R31 R32 R33 ] [ qfac * pixdim[3] * k ] [ qoffset_z ]

The qoffset_* shifts are in the NIFTI-1 header. Note that the center of the (i,j,k)=(0,0,0) voxel (first value in the dataset array) is just (x,y,z) = (qoffset_x,qoffset_y,qoffset_z).

The rotation matrix R is calculated from the quatern_* parameters. This calculation is described below.

The scaling factor qfac is either 1 or -1. The rotation matrix R defined by the quaternion parameters is "proper" (has determinant 1). This may not fit the needs of the data; for example, if the image grid is

i increases from Left-to-Right

j increases from Anterior-to-Posterior

k increases from Inferior-to-Superior

Then (i,j,k) is a left-handed triple. In this example, if qfac=1, the R matrix would have to be

[ 1 0 0 ]

[ 0 -1 0 ] which is "improper" (determinant = -1).

[ 0 0 1 ]

If we set qfac=-1, then the R matrix would be

[ 1 0 0 ]

[ 0 -1 0 ] which is proper.

[ 0 0 -1 ]

This R matrix is represented by quaternion [a,b,c,d] = [0,1,0,0] (which encodes a 180 degree rotation about the x-axis).

METHOD 3 (used when sform_code > 0):

The (x,y,z) coordinates are given by a general affine transformation of the (i,j,k) indexes:

x = srow_x[0] * i + srow_x[1] * j + srow_x[2] * k + srow_x[3]

y = srow_y[0] * i + srow_y[1] * j + srow_y[2] * k + srow_y[3]

z = srow_z[0] * i + srow_z[1] * j + srow_z[2] * k + srow_z[3]

The srow_* vectors are in the NIFTI_1 header. Note that no use is made of pixdim[] in this method.

WHY 3 METHODS?

Method 1 is provided only for backwards compatibility. The intention is that Method 2 (qform_code > 0) represents the nominal voxel locations

as reported by the scanner, or as rotated to some fiducial orientation and location. Method 3, if present (sform_code > 0), is to be used to give

the location of the voxels in some standard space. The sform_code indicates which standard space is present. Both methods 2 and 3 can be

present, and be useful in different contexts (method 2 for displaying the data on its original grid; method 3 for displaying it on a standard grid).

In this scheme, a dataset would originally be set up so that the Method 2 coordinates represent what the scanner reported. Later,

a registration to some standard space can be computed and inserted in the header. Image display software can use either transform,

depending on its purposes and needs.

In Method 2, the origin of coordinates would generally be whatever the scanner origin is; for example, in MRI, (0,0,0) is the center of the gradient coil.

In Method 3, the origin of coordinates would depend on the value of sform_code; for example, for the Talairach coordinate system, (0,0,0) corresponds to the Anterior Commissure.

Information from nifti1.h by RW Cox, NIH


Spatial and temporal dimensions

The codes below can be used in xyzt_units to indicate the units of pixdim. As noted earlier, dimensions 1,2,3 are for x,y,z; dimension 4 is for time (t).

- If dim[4]=1 or dim[0] < 4, there is no time axis.

- A single time series (no space) would be specified with

- dim[0] = 4 (for scalar data) or dim[0] = 5 (for vector data)

- dim[1] = dim[2] = dim[3] = 1

- dim[4] = number of time points

- pixdim[4] = time step

- xyzt_units indicates units of pixdim[4]

- dim[5] = number of values stored at each time point

Bits 0..2 of xyzt_units specify the units of pixdim[1..3] (e.g., spatial units are values 1..7). Bits 3..5 of xyzt_units specify the units of pixdim[4] (e.g., temporal units are multiples of 8).

This compression of 2 distinct concepts into 1 byte is due to the limited space available in the 348 byte ANALYZE 7.5 header. The macros XYZT_TO_SPACE and XYZT_TO_TIME can be used to mask off the undesired bits from the xyzt_units fields, leaving "pure" space and time codes. Inversely, the macro SPACE_TIME_TO_XYZT can be used to assemble a space code (0,1,2,...,7) with a time code (0,8,16,32,...,56) into the combined value for xyzt_units. Note that codes are provided to indicate the "time" axis units are actually frequency in Hertz (_HZ) or in part-per-million (_PPM).

The toffset field can be used to indicate a nonzero start point for the time axis. That is, time point #m is at t=toffset+m*pixdim[4] for m=0..dim[4]-1.

MRI-SPECIFIC SPATIAL AND TEMPORAL INFORMATION

A few fields are provided to store some extra information that is sometimes important when storing the image data from an FMRI time series experiment. (After processing such data into statistical images, these fields are not likely to be useful.)

{ freq_dim } = These fields encode which spatial dimension (1,2, or 3)

{ phase_dim } = corresponds to which acquisition dimension for MRI data.

{ slice_dim } =

Examples:

Rectangular scan multi-slice EPI:

freq_dim = 1 phase_dim = 2 slice_dim = 3 (or some permutation)

Spiral scan multi-slice EPI:

freq_dim = phase_dim = 0 slice_dim = 3

since the concepts of frequency- and phase-encoding directions don't apply to spiral scan

slice_duration = If this is positive, AND if slice_dim is nonzero, indicates the amount of time used to acquire 1 slice.

slice_duration*dim[slice_dim] can be less than pixdim[4] with a clustered acquisition method, for example.

slice_code = If this is nonzero, AND if slice_dim is nonzero, AND if slice_duration is positive, indicates the timing

pattern of the slice acquisition. The following codes are defined:

NIFTI_SLICE_SEQ_INC

NIFTI_SLICE_SEQ_DEC

NIFTI_SLICE_ALT_INC

NIFTI_SLICE_ALT_DEC

{ slice_start } = Indicates the start and end of the slice acquisition

{ slice_end } = pattern, when slice_code is nonzero. These values are present to allow for the possible addition of

"padded" slices at either end of the volume, which don't fit into the slice timing pattern. If there

are no padding slices, then slice_start=0 and lice_end=dim[slice_dim]-1 are the correct values.

For these values to be meaningful, slice_start must be non-negative and slice_end must be greater than slice_start.

The following table indicates the slice timing pattern, relative to time=0 for the first slice acquired, for some sample cases. Here,

dim[slice_dim]=7 (there are 7 slices, labeled 0..6), slice_duration=0.1, and slice_start=1, slice_end=5 (1 padded slice on each end).

slice

index SEQ_INC SEQ_DEC ALT_INC ALT_DEC

6 -- n/a n/a n/a n/a n/a = not applicable

5 -- 0.4 0.0 0.2 0.0 (slice time offset

4 -- 0.3 0.1 0.4 0.3 doesn't apply to

3 -- 0.2 0.2 0.1 0.1 slices outside range

2 -- 0.1 0.3 0.3 0.4 slice_start..slice_end)

1 -- 0.0 0.4 0.0 0.2

0 -- n/a n/a n/a n/a

The fields freq_dim, phase_dim, slice_dim are all squished into the single byte field dim_info (2 bits each, since the values for each field are

limited to the range 0..3). This unpleasantness is due to lack of space in the 348 byte allowance.

The macros DIM_INFO_TO_FREQ_DIM, DIM_INFO_TO_PHASE_DIM, and DIM_INFO_TO_SLICE_DIM can be used to extract these values from the

dim_info byte. The macro FPS_INTO_DIM_INFO can be used to put these 3 values into the dim_info byte.

Documentation from nifti1.h by RW Cox, NIH


Quaternions

QUATERNION REPRESENTATION OF ROTATION MATRIX (METHOD 2)

The orientation of the (x,y,z) axes relative to the (i,j,k) axes in 3D space is specified using a unit quaternion [a,b,c,d], where

a*a+b*b+c*c+d*d=1. The (b,c,d) values are all that is needed, since we require that a = sqrt(1.0-b*b+c*c+d*d) be nonnegative. The (b,c,d)

values are stored in the (quatern_b,quatern_c,quatern_d) fields.

The quaternion representation is chosen for its compactness in representing rotations. The (proper) 3x3 rotation matrix that

corresponds to [a,b,c,d] is

[ a*a+b*b-c*c-d*d 2*b*c-2*a*d 2*b*d+2*a*c ]

R = [ 2*b*c+2*a*d a*a+c*c-b*b-d*d 2*c*d-2*a*b ]

[ 2*b*d-2*a*c 2*c*d+2*a*b a*a+d*d-c*c-b*b ]

[ R11 R12 R13 ]

= [ R21 R22 R23 ]

[ R31 R32 R33 ]

If (p,q,r) is a unit 3-vector, then rotation of angle h about that direction is represented by the quaternion [a,b,c,d] = [cos(h/2), p*sin(h/2), q*sin(h/2), r*sin(h/2)].

Requiring a >= 0 is equivalent to requiring -Pi <= h <= Pi. (Note that [-a,-b,-c,-d] represents the same rotation as [a,b,c,d]; there are 2 quaternions that can be used to represent a given rotation matrix R.)

To rotate a 3-vector (x,y,z) using quaternions, we compute the quaternion product [0,x',y',z'] = [a,b,c,d] * [0,x,y,z] * [a,-b,-c,-d] which is equivalent to the matrix-vector multiply

[ x' ] [ x ]

[ y' ] = R [ y ] (equivalence depends on a*a+b*b+c*c+d*d=1)

[ z' ] [ z ]

Multiplication of 2 quaternions is defined by the following: [a,b,c,d] = a*1 + b*I + c*J + d*K

where

I*I = J*J = K*K = -1 (I,J,K are square roots of -1)

I*J = K J*K = I K*I = J

J*I = -K K*J = -I I*K = -J (not commutative!)

For example [a,b,0,0] * [0,0,0,1] = [0,-b,0,a] since this expands to (a+b*I)*(K) = (a*K+b*I*K) = (a*K-b*J).

The above formula shows how to go from quaternion (b,c,d) to rotation matrix and direction cosines. Conversely, given R, we can compute the fields for the NIFTI-1 header by

a = 0.5 * sqrt(1+R11+R22+R33) (not stored)

b = 0.25 * (R32-R23) / a => quatern_b

c = 0.25 * (R13-R31) / a => quatern_c

d = 0.25 * (R21-R12) / a => quatern_d

If a = 0 (a 180 degree rotation), alternative formulas are needed. See the nifti1_io.c function mat44_to_quatern() for an implementation of the various cases in converting R to [a,b,c,d].

Note that R-transpose (= R-inverse) would lead to the quaternion [a,-b,-c,-d].

The choice to specify the qoffset_x (etc.) values in the final coordinate system is partly to make it easy to convert DICOM images to this format. The DICOM attribute "Image Position (Patient)" (0020,0032) stores the (Xd,Yd,Zd) coordinates of the center of the first voxel. Here, (Xd,Yd,Zd) refer to DICOM coordinates, and Xd=-x, Yd=-y, Zd=z, where (x,y,z) refers to the NIFTI coordinate system discussed above.

(i.e., DICOM +Xd is Left, +Yd is Posterior, +Zd is Superior,

whereas +x is Right, +y is Anterior , +z is Superior. )

Thus, if the (0020,0032) DICOM attribute is extracted into (px,py,pz), then qoffset_x = -px qoffset_y = -py qoffset_z = pz is a reasonable setting when qform_code=NIFTI_XFORM_SCANNER_ANAT. That is, DICOM's coordinate system is 180 degrees rotated about the z-axis from the neuroscience/NIFTI coordinate system. To transform between DICOM and NIFTI, you just have to negate the x- and y-coordinates.

The DICOM attribute (0020,0037) "Image Orientation (Patient)" gives the orientation of the x- and y-axes of the image data in terms of 2 3-vectors.

The first vector is a unit vector along the x-axis, and the second is along the y-axis. If the (0020,0037) attribute is extracted into the value (xa,xb,xc,ya,yb,yc), then the first two columns of the R matrix would be

[ -xa -ya ]

[ -xb -yb ]

[ xc yc ]

The negations are because DICOM's x- and y-axes are reversed relative to NIFTI's. The third column of the R matrix gives the direction of displacement (relative to the subject) along the slice-wise direction. This orientation is not encoded in the DICOM standard in a simple way; DICOM is mostly concerned with 2D images. The third column of R will be either the cross-product of the first 2 columns or its negative. It is possible to infer the sign of the 3rd column by examining the coordinates in DICOM attribute (0020,0032) "Image Position (Patient)" for successive slices. However, this method occasionally fails for reasons that I (RW Cox) do not understand.

Information provided in nifti1.h by RW Cox


Dataset import

Import of nifti-1 data set

A dataset will be imported in the way depicted in the flowchart below.


NIfTI-1 io

Available functions in c++ by Robert Cox:

Other conversion tools:

> Java: Kate Fissell

> Java: Daniel Valentino

> Matlab: John Ashburner


Overview

This is the first topic in your project. Delete this text and replace it with your own. To add a new topic, click the New Topic button on the toolbar.

To learn more about the WYSIWYG Editor, press F1 (with your cursor in this pane) to display Help.


Quaternion computation

To convert from a rotation matrix to a quaternion one needs to compute the scalar a and the coefficients b, c and d for the basis quaternions i, j and k

(see right side of figure). Using quaternions facilitates the representation and application of a rotation.

Figure 2: Components of rotation matrix and quaternion

To be able to write the quaternion in the form (cos , sin v), the quaternion

q has to be normalized to a unit quaternion. The quaternion can be divided

by its norm for normalization so that kqk = 1.

Figure 3: Conversion from a quaternion to a 4 x 4 rotation matrix

The normalization of a rotation matrix using Euler angles is much more computationally expensive, since the matrix M has to be replaced by M(MTM)−1/2. Normalization of the matrix M is necessary to prevent the matrix to become non-orthogonal, which would result in rotation errors.

To obtain a rotation matrix from a quaternion, the Euler angles phi, theta and psi need to be computed (see figure above).

For specific information about the use of quaternions in nifti-1 see the mat44_to_quatern( <params> ) and quatern_to_mat44( <params> ) functions

in the nifti1_io.h and nifti1_io.c code from Robert Cox. Some general information is available in [1] and [2].

References

[1] R. Mukundan. Quaternions: From classical mechanics to computer graphics,

and beyond. In Proceedings of the 7th Asian Technology Conference in Mathematics 2002, 2002.

[2] E.W. Weisstein. Quaternion. From Mathworld – a Wolfram Web Resource. http://mathworld.wolfram.com/Quaternion.html.