Monday, April 23, 2007

medcon命令行

ProgramCLI

The command-line interface program has a few more features than its graphical user interface counterpart. It can be used for batch conversion, debugging image headers, printout pixel values, hack files with Acr/Nema tags and a little more. Besides, it can be very useful in powerfull Unix shell-scripts too! All you have to do is giving it the proper options ... ;-)

The man-page <medcon.1> tells you all about its options:

SYNOPSIS

    medcon [options] -f <files> ... 

FLAGS

-f, --file, --files <files> ...

    Read a list of files. 

OPTIONS

-8, --indexed-color

This color mode forces 24-bit RGB color images being reduced to an 8-bit indexed colormap. For color reduction in combination with dithering, see the -dith option.

-24, --true-color

This color mode keeps a 24-bit image as is.

-alias, --alias-naming

Generate filenames based on patient and study information. The resulting basename is:
<patient_name>+<study_descr>+<study_date>+<study_time>+<nr_series>+<nr_acquisition>+<nr_instance>
with the latter three id's applied in case the originating format is DICOM or Acr/Nema. See also -noprefix. Since Analyze does not have a patient_name, patient_id is used instead.

-anon, --anonymous

Make patient and study related entries anonymous (filled with 'X'). This option can not be used with option -ident.

-b8, --unsigned-char
-b16, --signed-short
-b16.12

Force writing of Uint8 or Int16 pixels. The special option -b16.12 only uses 12 bits, as unsigned however. With these options one can lose the quantified float values when the new format doesn't support a global rescale factor or slope/intercept.

-big, --big-endian

Force writing of file in BIG endian type when supported by the format (see -little).

-byframe, --sort-by-frame

Set sort order in ECAT by frames, instead of the default anatomical sort (based on slice location). Indentical planes in each frame will be grouped together. You don't want this.

-c, --convert <format> ...

NotationFormat
"acr"Acr/Nema 2.0
"anlz"Analyze (SPM)
"conc"Concorde/microPET
"dicom"DICOM 3.0 (NM)
"ecat"CTI ECAT 6.4
"gif"Gif89a
"intf"InterFile 3.3
"inw"INW (RUG)
"nifti"NIfTI Analyze
"png"PNG
"bin"Raw binary
"ascii"Raw ascii
Convert with a list of formats to convert to. Use the above notation without quotes on the command line. You can't use this option with -p.

-contrast, --enable-contrast

Apply (DICOM) window centre/width contrast remapping. Although this may improve the display of images, any manufacturer independent pixel values (like HU, SUV) with quantitation options -qc or -qs will be lost.

-cor, --coronal

Reslice the images of a volume into a coronal projection while preserving the real world dimensions.

-crop=<X>:<Y>:<W>:<H>, --crop-images=<X>:<Y>:<W>:<H>

This option allows to crop an equal frame from all images at <X>:<Y> where width and height are <W>:<H>. The upper-left corner of an image is at 0:0.

-cs, --cine-sorting

Apply cine sorting, 1st image of each time frame, 2nd image of each time frame, 3rd image of each time frame and so on. Reapplying does NOT undo this sorting. For this you need option -cu.

-cu, --cine-undo

Undo the cine sorting (as a result from the option -cs).

-cw=<centre>:<width>

Remap contrast using specified centre/width values. No spaces are allowed within this option. See also -contrast option.

-d, --debug

Show debug info. After reading a file, the program will display the contents of the internal FILEINFO structure.

-dith, --dither-color

Use dithering to improve quality of color reduction (from RGB to 8-bit indexed).

-e, --extract [image ranges ...]

A routine to extract images interactively, unless you specify normal style image ranges directly on the command-line separated by spaces. In normal style it is also possible to reorder the sequence of images. You need to specify an output conversion format (see option -c). Note that the extraction does NOT addapt the centre-centre slice separations. In other words, proper volume measurements could be lost.
        Selection Type? 1=normal 2=ecat

Normal Style
------------
- Any number must be one-based (0 = All reversed)
- Syntax of range: X...Y or X-Y
- Syntax of interval: X:S:Y (S = step)
- The list is sequence sensitive!

Give a list of images to extract?

Ecat Style
----------
- Any number must be one-based (0 = All)
- Syntax of range: X...Y or X-Y
- Syntax of interval: X:S:Y (S = step)

Give planes list?
Give frames list?
Give gates list?
Give beds list?

-ean, --echo-alias-name

A convenience function which quickly echoes the alias or human readable filename on screen, without any delay of image processing. For the syntax of this alias filename, see option -alias. The output could then be used in a script, for example to make interpretable links towards cryptic numbered files resulting from a DICOM series.

-fb-none, --without-fallback
-fb-anlz, --fallback-analyze
-fb-conc, --fallback-concorde
-fb-dicom, --fallback-dicom
-fb-ecat, --fallback-ecat

Disable or specify a fallback read format in case the autodetect failed.

-fh, --flip-horizontal
-fv, --flip-vertical

Flip images horizontal (-fh) along the X-axis, vertical (-fv) along the Y-axis respectively. Parameters such as slice orientation are NOT changed. See also -rs option.

-fmosaic=<W>x<H>x<N>, --force-mosaic=<W>x<H>x<N>

Enforce the mosaic file support for DICOM or Acr/Nema formats. The *stamps* will be splitted into separate slices according to the values supplied on the command-line. See also extra options -interl and -mfixv. The preset arguments are:
       <W> = pixel width  of image stamps (X)
<H> = pixel height of image stamps (Y)
<N> = total number of image stamps (Z)

medcon -f imagefile -fmosaic=64x64x32

-g, --make-gray

Remap coloured images to gray. This is necessary when you convert to formats which only support a grayscale colormap!

-gap, --spacing-true-gap

The spacing between slices is the true gap/overlap between sequential slices. In contrary to the default behaviour where the spacing between slices is measured from the centre to centre of two adjacent slices, therefor including the gap/overlap. Applied in DICOM and Acr/Nema.

-hackacr, --hack-acrtags

Enables you to hack a file that contains Acr/Nema tags hidden somewhere. Some proprietary image formats do contain tags but are placed after some unknown headerinformation. This option will try to find some readable tags in the first 2048 bytes after which it will give some possible hints to get the images out of the file with the use of the interactive reading procedure (see -i). Ofcourse, this experimental procedure can fail badly ...

-i, --interactive

Selects the interactive reading procedure. Normally the program automatically detects the format or uses 'ecat' (or 'dicom') as default. With the interactive procedure it could be possible to read an uncompressed, unsupported format by answering the following questions:
        Number of images?
General header offset to binary data?
Image header offset to binary data?
Image header repeated before each image?
Swap the pixel bytes?
Same characteristics for all images?
---
Absolute offset in bytes?
Image columns?
Image rows?
Pixel data type?
Redo input?
The GUI allow to save such raw predef input (RPI) files, that can be used in a redirect statement:
        medcon -f unsupported.img -c intf -i < predef.rpi
Doing so, you can create small scripts that will read and convert your unsupported images at once.

-ident, --identify

An interactive routine to specify the patient and study related information. This option can not be used with the option -anon. The questions asked are:
        Give patient name?
Give patient id?
Select patient sex?
Give study description?
Give study name/p-number?

-implicit, --write-implicit

Another DICOM related option to enforce the implicit VR little transfer syntax as output, instead of the default explicit transfer syntax.

-interl, --mosaic-interlaced

An extra option used in combination with forced mosaic (-fmosaic). The option indicates that the slices in the original mosaic are in fact interlaced. See also options -fmosaic and -mfixv.

-little, --little-endian

Force writing of LITTLE endian files when supported by the format (see -big).

-lut, --load-lut <filename>

Load an external LUT color scheme: a dead simple file of 768 bytes consisting of 256 x red, 256 x green and 256 x blue byte values to make up the necessary 256 RGB triplets.

-mh, --map-hotmetal
-mr, --map-rainbow
-mi, --map-inverted
-mc, --map-combined

Selects the hotmetal, rainbow, invers (gray) or combined colormap. This is only usefull to GIF89a or PNG.

-mfixv, --mosaic-fixvoxel

Another extra option used in combination with forced mosaic (-fmosaic). Choosing this option will rescale the real world voxel dimensions by the mosaic factor. See also -fmosaic and -interl.

-mosaic --enable-mosaic

Enable mosaic file support in DICOM or Acr/Nema format. The *stamps* will be splitted into separate slices according to values found in the file. To support other type of mosaic files, see option -fmosaic.

-n, --negatives

Preserve negative values. When not selected, all negative values are put to zero. In combination with quantitation (see -qs or -qc) the requested format must support pixels of type float, a global rescale factor or the more generic slope/intercept concept in order to preserve the (negative and positive) quantified values.

-nf, --norm-over-frames

Normalize with minimum/maximum values found over images in a frame group (in case the original format has different frames). The default behaviour is normalization with minimum/maximum values found over all images. This can be important when the requested format requires a rescaling to a new pixeltype. The original pixel values then need to be rescaled to the new pixeltype boundaries based on the minimum/maximum values.

-nometa, --write-without-meta

Write DICOM files without the part 10 meta header (group 0x0002).

-nopath, --ignore-path

Ignore absolute path mentioned in the "name of data file" key of an InterFile header. Do make sure then that the data file resides in the same directory as the header file.

-noprefix, --without-prefix

This option disables the numbered prefix in the output filename. In combination with the -alias option, one could create human readable and alphabetical sorted files from DICOM or Acr/Nema multiple file volumes.

-o, --output-name filename

Changes output filename for ALL files to be created. It is allowed to specify a full directory path as well. However, a full path disables unique filename prefixing.

-one, --single-file

Write header and image to same file, as allowed for InterFile.

-optgif, --options-gif

Define some GIF options when converting to the GIF format. Without this option a loop and background color are defined by default. This interactive routine asks the following questions:
        Select color map?
Insert a display loop?
Delay 1/100ths of a second?
Insert a transparent color?
Transparent color?
Background color?

-optspm, --options-spm

Define some SPM options (origins) when converting to the Analyze format. The quantitation is not set. See also -spm & -ar. The interactive routine asks the following questions:
        Origin X?
Origin Y?
Origin Z?

-p, --print-values

Show some specified pixel values. This is an interactive routine. Calibration and negative pixels are preserved automatically. You need to specify the -qs to preserve the quantification instead of the calibration. You can not use this option with -c. See also -pa option for a non-interactive routine.
        - Finish the list with a negative number
- Any number must be one-based (0 = All)
- The syntax of a range: X...Y or X-Y
- Just type <enter> for the entire range

Selection Type? 1=normal 2=ecat

Normal Style
------------

Give a list of image numbers?
Give a list of pixels x,y ?

Ecat Style
----------

Give planes list?
Give frames list?
Give gates list?
Give beds list?
Give a list of pixels x,y ?

-pa, --print-all-values

Show all pixel values. This option is identical to -p, but doesn't require user input.

-pad, --pad-around
-padtl, --pad-top-left
-padbr, --pad-bottom-right

Increasing the slice matrix is done by padding an image with the lowest pixel value. The options above allow for different padding modes. Matrix changes happen when the output format does not allow differently sized images, and in case an -sqr or -sqr2 option was selected.

-preacq, --prefix-acquisition
-preser, --prefix-series

Respectivily use acquisition or series value in the numbered prefix of the new filename. This is useful for alphabetical file ordering, where leading zeros in DICOM elements are missing. See also -alias.

-q, --quantitation

Enable quantitation using all scale factors (for now alias for -qc option).

-qs, --quantification

A first scaling option to preserve the (ECAT) quantification (a) or to consider a first linear scaling slope with intercept (b).
        qpv = ppv * quant_scale [counts/second/pixel] (a)
qpv = ppv * slope + intercept (b)

qpv = quantified pixel value
ppv = plain pixel value
The 'quant_scale' factor normalizes all images in the file; quite important for merging purposes. When the corresponding format can not hold a 'quant_scale' factor for each image, the pixel values are saved as floats. Therefore, the highest pixel precision for correct quantitation is float, not double!
If the format does not support floats, the quantified pixel values get rescaled to an integer. Then only formats that support a global scaling factor or slope/intercept pair will preserve those quantified values.
Note that this option can not be used with -qc.

-qc, --calibration

A second quantitation option to preserve the (ECAT) quantification as well as the (ECAT) calibration (a) or in general, using two rescale slopes with an intercept (b). These should normally transform pixels into manufacturer independent values. So one can assume that after a calibration, the new pixels will represent a real world unit (like concentration values (SUV), hounsfield units (HU) and alike).
        cpv = ppv * quant_scale * calibr_fctr [uCi/ml] (a)
cpv = ppv * slope1 * slope2 + intercept (b)

cpv = calibrated pixel value
ppv = plain pixel value
qpv = quantified pixel value = ppv * quant_scale
The 'quant_scale' factor normalizes all images in the file; very important for merging purposes. The 'calibr_fctr' rescales the qpv-values to a new unit. When the corresponding format can not hold a compound factor for each image, the quantified values will be saved as floats. Therefore, the highest pixel precision for correct quantification is float and not double!
If the format does not support floats, the calibrated pixel values are rescaled to an integer type. Only formats that support a global scaling factor or slope/intercept pair preserve those calibrated values.
Note that in case of conversion, this option can not be used with -qs.

-r, --rename-file

Rename the file basename. This option is only useful in case of conversion.

-rs, --reverse-slices

Reverse all the slices along the Z-axis. Parameters such as slice orientation are NOT changed. See also the -fh and -fv options.

-s, --silent

Suppress all message, warning and error dialogs.

-sag, --sagittal

Reslice the images of a volume into a sagittal projection while preserving the real world dimensions.

-si=<slope>:<intercept>

Force remap of pixel values using specified slope/intercept (y = s*x + i). The quantitation option -qc is enabled by default. No spaces are allowed within this option.

-skip1, --skip-preview-slice

Skip the first image in an InterFile. In other words, the first image in the array will simply be ignored. Use this only when you are sure that the InterFile does contain an annoying/confusing preview slice.

-split4d, -splitf, --split-frames
-split3d, -splits, --split-slices

Write out a study into separate files, one for each volume in a time frame (--split-frames) or each image slice (--split-slices) individually. The names of the files created will have an extra index number. See also -stack3d and -stack4d as opposite options.

-spm, --analyze-spm

Considering Analyze files for/from SPM. In this case the global scaling factor hidden in imd.funused[1] will be used, as well as the hidden offset value in imd.funused[0].
In case of quantitation, the default output pixel type is float. This option allows to write integers combined with a global scale factor. To actually use the scaling factor, you must select a quantitation option like -qs or -qc as well.
See also -ar & -optspm.

-sqr, --make-square

Make all image matrices square, using the largest dimension.

-sqr2, --make-square-two

Make all image matrices square, using the nearest power of two (between 64, 128, 256, 512 and 1024).

-stack4d, -stackf, --stack-frames
-stack3d, -stacks, --stack-slices

Write separate studies into one file. The --stack-slices option allows to write single image slice files into one 3D volume, while the --stack-frames option allows volumes of different time frames being written into one 4D file. The sequence of stacking is based on the file sequence given at the argument line. See also -split3d and -split4d as the opposite options.

-tra, --transverse

Reslice the images of a volume into a transverse projection while preserving the real world dimensions.

-uin, --use-institution-name namestring

Change the program's default institution name, which is applied on studies without one. This does not override existing values. For a namestring with spaces, group between double quotes.

-v, --verbose

Verbose mode. Show some explaining messages during the reading and writing of files.

-vifi, --edit-fileinfo

An interactive routine for editing voxel, array, slice and orient related entries in the FILEINFO structure.

-w, --overwrite-files

Allow overwrite of existing files, without warning.

NOTES

When no conversion was selected, the program will display the header information of each file.
When conversion was choosen, the program will automatically create new filenames in the current directory with the following syntax:
          mXXX-filename.ext
'XXX' a number representing the XXX-th conversion
'ext' a corresponding extension of the new format

Acr/Nema -> .ima
Analyze -> .hdr + .img
Dicom -> .dcm
Ecat -> .img
Gif -> .gif
InterFile -> .h33 + .i33
INW -> .im
NIfTI -> .nii
PNG -> .png
Raw Ascii -> .asc
Raw Binary -> .bin
Some special remarks related to reading from stdin or writing to stdout.
a) reading from stdin:
Enable this by using an "-" mark instead of the list of input files.
1. redirect:
medcon -f - < inputfile
This is supported for all formats and shouldn't cause any particular problems. Ofcourse, interactive routines are disabled because stdin is now in use by the image input.
2. pipes:
cat inputfile | medcon -f - format
Actually, this way only one or two formats are supported since seek() calls are not possible during pipes. The fact is that most of our formats are read using those seek() calls. In normal operation we already need a quick sneak in the file to determine the format. Because this fseek() isn't allowed, you must supply at least the input format too.
b) writing to stdout:
Enabled by using an extra "-" mark on the conversion list.
medcon -f inputfile -c - format
Only one inputfile is allowed. The converted output will be send to stdout.
In case of dual file formats such as Analyze or InterFile, the header information will be send to stderr. The reference to the image file in the header of an InterFile will ofcourse be wrong (since the program is not capable of knowing the resulting filename).
In case of RAW or ASCII output, the program will print the content of the internal FILEINFO struct to stderr as well. Please note that the (t)csh shell does not allow to catch stderr or stdout separately. In case of the bash shell, it is possible to say:
medcon -f inputfile -c - intf -b16.12 -qc 1>image 2>header

EXAMPLES

  1. To display the image headers:
     medcon -f filename1.gz filename2 | more  
  1. To convert the images:
     medcon -f filename1 filename2 -c gif acr intf  
  1. To read interactively:
     medcon -i -f filename.Z -c ecat  
  1. To extract alternate images:
     medcon -e 1:2:20 -f filename -c gif  
  1. To print out pixel values
     medcon -p -f filename  
  1. Send raw images to standard output
     medcon -f filename -c - bin  

Sunday, April 22, 2007

Analyze 文件格式

Mayo/SPM "Analyze" Format Spec Compilation
Article created: 2003-06-22

Contents

  • Overview
  • See Also Orientation and Voxel-Order Terminology Page
  • Header File (.hdr)
  •  Image file (.img) Overview
  • Voxel Order
  • "Strict" Analyze 7.5 Voxel Order Treatment
  • The Problem With hist.orient Field
  • Analyze Format "In The Wild"
  • Future
  • 2003-11-04 Update: Darren Weber  posted some relevent links to the FreeSurfer list, here are some pointers.
  • 2004-04-18 Update: Expanded notes on hist.orient in response to apparent error in NIfTI interpretation.
  • Acknowledgements

Overview

Mayo Clinic Analyze 7.5 format is a file format for storing MRI data. An Analyze 7.5 data set consists of two files:

  • Header file (something.hdr): Provides dimensional, identifying and some processing history information
  • Image file (something.img): Stream of voxels, whose datatype and ordering are described by the header file

Although this is conceptually straightforward, there is enough variation in how different software treats voxel ordering (orientation) that getting the desired results can be tricky.

This document is an attempt to compile definitive information from a number of sources. It may continue to be a work-in-progress.

See Also Orientation/Voxel-Order Terminology Page

The following discussion relies on some familiarity with terminology for axes, orientation, voxel order and so on. Some of this terminology is used in multiple and sometimes contradictory or opposite ways. For details see the Orientation and Voxel-Order Terminology page.

Header File (.hdr)

The following table lists the Analyze format as specified by Mayo Clinic, showing variations used in SPM and by Darren Weber's mri_toolbox. Not all software understands all fields, as further discussed in the Image File section later. See also the list of notes below this table.



  Mayo Analyze 7.5 SPM99 SPM2 mri_toolbox
Row OS Sec name type name type AKA name type AKA name type Short Description (Mayo doc, plus other notes)
1 0 key sizeof_hdr int32







Must indicate the byte size of the header file.
Non SPM2: Always 348, used to test big/little-endian).
SPM2: If >348 indicates extended header
2 4   data_type uchar[10]








3 14   db_name uchar[18]








4 32   extents int32







Should be 16384, the image file is created as contiguous with a minimum extent size.
5 36   session_error int16








6 38   regular uchar







Must be "r" to indicate that all images and volumes are the same size.
7 39   hkey_un0 uchar








8 40 dim dim[0] int16







Number of dimensions in database; usually 4
9 42   dim[1] int16

DIM




Image X dimension; number of pixels in an image row
10 44   dim[2] int16

DIM




Image Y dimension; number of pixel rows in slice
11 46   dim[3] int16

DIM




Volume Z dimension; number of slices in a volume
12 48   dim[4] int16







Time points, number of volumes in database.
13 50   dim[5] int16







undoc
14 52   dim[6] int16







undoc
15 54   dim[7] int16







undoc
16 56   vox_units uchar[4]







spatial units of measure for a voxel
17 60   cal_units uchar[8]







name of the calibration unit
18 68   unused1 int16








19 70   datatype int16







See DT_xxx values
20 72   bitpix int16







bits per pixel; 1, 8, 16, 32, or 64.
21 74   dim_un0 int16







unused
22 76   pixdim[0] float








23 80   pixdim[1] float







voxel width in mm.
24 84   pixdim[2] float







voxel height in mm.
25 88   pixdim[3] float







slice thickness in mm.
26 92   pixdim[4] float







undoc
27 96   pixdim[5] float







undoc
28 100   pixdim[6] float







undoc
29 104   pixdim[7] float







undoc
30 108   vox_offset float







Byte offset in the .img file at which voxels start. This value can be negative to specify that the absolute value is applied for every image in the file.
31 112   funused1 float funused1 float SCALE funused1      float scal roi_scale     float SPM: Scale factor
32 116   funused2 float funused2 float
funused2      float dcoff funused1      float SPM2: image intensity zero-intercept
33 120   funused3 float funused3 float
funused3      float
funused2      float
34 124   cal_max float







max calibration value
35 128   cal_min float







min calibration value
36 132   compressed float








37 136   verified float








38 140   glmax int32







max pixel value for entire database
39 144   glmin int32







min pixel value for entire database
40 148 hist descrip uchar[80]








41 228   aux_file uchar[24]








42 252   orient uchar







slice orientation for this dataset: See separate note
43 253   originator uchar[10] origin[0] int16 ORIGIN origin[0] int16
originator    uchar[10] SPM99: X near Anterior Commissure
44
 

origin[1] int16 ORIGIN origin[1] int16


SPM99: Y near Anterior Commissure
45
 

origin[2] int16 ORIGIN origin[2] int16


SPM99: Z near Anterior Commissure
46
 

origin[3] int16 ORIGIN origin[3] int16



47
 

origin[4] int16 ORIGIN origin[4] int16



48 263   generated uchar[10]








49 273   scannum uchar[10]








50 283   patient_id uchar[10]








51 293   exp_date uchar[10]








52 303   exp_time uchar[10]








53 313   hist_un0 uchar[3]








54 316   views int32








55 320   vols_added int32








56 324   start_field int32








57 328   field_skip int32








58 332   omax int32








59 336   omin int32








60 340   smax  int32








61 344   smin int32









348   TOTAL BYTES









.

Key Source
Mayo Analyze 7.5 Mayo Clinic Analyze 7.5 Format: www.mayo.edu/bir/PDF/ANALYZE75.pdf
SPM99 SPM99 spm_hread.m    SPM Home: www.fil.ion.ucl.ac.uk/spm
SPM2 SPM2 spm_read_hdr.m
mri_toolbox Darren Weber's mri_toolbox v1.8: Matlab EEG-MRI Toolbox
   

.

datatype DT_xxx Value Description
DT_NONE 0  
DT_UNKNOWN 0  
DT_BINARY 1 1 bit per voxel
DT_UNSIGNED_CHAR 2 8 bits per voxel
DT_SIGNED_SHORT 4 16 bits per voxel
DT_SIGNED_INT 8 32 bits per voxel
DT_FLOAT 16 32 bits per voxel (single)
DT_COMPLEX 32 2 x 32 bit single
DT_DOUBLE 64 64 bits per voxel
DT_RGB 128  
DT_ALL 255  

.

Notes
unused8 to unused14 The Mayo Format Doc ANALYZE75.pdf lists fields unused8-14 at Offsets 56-69. However, their dbh.h file lists vox_units and cal_units in this area, and even the comments in the pdf file refer to vox_units --  indicating that perhaps their unused8-14 fields are left over from an earlier generation of source code.
sizeof_hdr This field implies that Analyze format was originally intended to be extensible, but in practice this did not happen, and instead the file size (and hence the value of this field) is 348. Software commonly tests the value in this field to detect whether the byte ordering is Big-Endian or Little-Endian.
(Note that future variants of Analyze format with longer files are anticipated. See also SPM2 note below. Hopefully each extended format will be readily identifiable if longer than 348 bytes even if byte-order is not known).
MatLab array indices I have shown array indices as based at 0, as for example from C language. If using them from MatLab I believe it's necessary to treat arrays as one-based.
hist.orient Subject of more discussion below
SPM2 extension SPM2 source code (spm_read_hdr.m) indicates that it can employ an extension to the size of the hdr file to contain further info.

.

Image file (.img) Overview

An Analyze 7.5 image file  consists of one long stream of voxel intensities. The format and ordering of the img file is described as follows:

Format aspect Field etc Discussion
Data type dim.datatype A particular img file represents voxel intensities using from one bit to 8 bytes per voxel, according to the value of this field. See the DT_xxx values.
byte order --- Little-endian vs Big-Endian-- software must test for which byte-order is in use in this file. See note on sizeof_hdr as a test field.
Voxel order hist.orient
dim.pixdim
others?
See further details in discussion below
Multiple volumes --- One after another in the file. The key.regular field suggests that volumes could be different sizes etc, but that would presumably also require multiple dim sections, and this does not seem to occur.
     

Voxel Order

Of crucial importance is the ordering of voxels within the img file. Unfortunately, the document "Mayo Clinic Analyze 7.5 Format" omits some essential details on this (possibly an oversight). Whether as a result of this or not, there is considerable variation in the way different software developers have treated voxel storage order.

Consequently, there are two different stories to be told:

  • The "strictly correct" way to use Analyze 7.5 format -- if you have control of all aspects or are working only with similarly correct software.
     
  • In The Wild: What might we expect from real world files operated upon by a variety of software?

"Strict" Analyze 7.5 Voxel Order Treatment

My understanding of this owes a great deal to the patient persuasion of Darren Weber (and his thoroughly researched mri_toolbox source code). I have since corroborated his detective work with inputs from another group, so this looks like a solid case, even if the info is hard to come by (less so thanks to Darren of course).

  • There is a default voxel ordering
     
  • A different ordering may be specified using the hist.orient field. Mayo's Format document describes the history structure as optional, but since all hdr files include it, "optional" must correspond to hist.orient having a value of zero.

Consolidating the notes in Darren's source code, which is based on email from AnalyzeSupport.com, we get.

hist.orient Mayo name Voxel[Index0, Index1, Index2]
Index0 Index1 Index2
0 (default) transverse unflipped R-L P-A I-S
1 coronal unflipped R-L I-S P-A
2 sagittal unflipped P-A I-S R-L
3 transverse flipped R-L A-P I-S
4 coronal flipped R-L S-I P-A
5 sagittal flipped P-A S-I R-L
Note: Index0 is fastest-varying (innermost-nested) index, Index2 the outermost.
Index0..Index2 are often called X, Y, Z, but I am trying to avoid confusion with spatial coordinates.
2004-04-18: See later section for comparison to NIfTI

The Problem With hist.orient Field

Aside from the hard-to-come-by documentation of hist.orient, the major shortcoming of this field as a code for voxel order is that it only covers 6 of the 48 possible orders.  This means that software authors who wanted to be able to honor some voxel-order scheme did not have a field provided. In particular, though hist.orient provides the popular (R-L, P-A, I-S) orientation, it omits the L-R flip of this, (L-R, P-A, I-S).

This has proven to be a critical issue. Neither end users nor software authors have been held back from reorienting their data, either to create different views in viewers which lack orientation control, or for convenience in processing the data.

In recognition of this fact, one of the most hopeful thrusts of the NIfTI initiative (more below) is to establish a standard way to use this field. (It can't arrive soon enough!).

Analyze Format "In The Wild"

Below are some variations in the way software deals with Analyze format voxel order, with implications for results when using these packages, or files produced by these packages. (This is not a criticism of these packages so much as simply a caution that given the uncertainty in the way voxel-order is actually handled by software it's important to be aware of the hazard and prepare to take remedial action.)

Some important factors:

  • hist.orient: Software may or may not attend to the hist.orient field
     
  • negative dim.pixdim values: Some have adopted negative pixdims to indicate voxels stored in reverse order for that dimension
     
  • SPM99 normalization: SPM99's normalization flips the R-L ordering of data, and SPM99 does not use the hist.orient field. This would tend to create a mix of (R-L, P-A, I-S) and (L-R, P-A, I-S) files in the same environment. (Note that (L-R, P-A, I-S) is not one of the orientations that can be specified by the hist.orient field anyway).

In the list below, I won't attempt to get the exact details correct enough for programmer satisfaction, but simply to indicate where the particular software differs from "Strict" Analyze 7.5 format in some manner. The main point is to raise awareness that orientation can't be taken for granted.

Software Version hist.orient -negative pixdims Orientation Treatment
SPM 99 ignores not sure Pre-normalization: assumes voxels in (R-L, P-A, I-S) order.
Normalization creates data in (L-R, P-A, I-S) order
SPM adds a third file (something.mat) with a transformation matrix -- not sure how this impacts data order
There is also a sptl_Ornt variable
SPM 2 ignores not sure Change in voxel order: "images spatially normalised using SPM99 or earlier will need to be spatially normalised again" according to SPM docs.
AFNI 2003-04 ignores ignores Various AFNI utilities convert to or from Analyze format. Generally you can set parameters to describe any input voxel order, or to specify any output voxel order, disregarding hist.orient or -ve pixdims.  Program to3d attempts to detect SPM-normalized files by looking for SPM's special usage of the hist.origin fields.
According to AFNI docs, the AFNI viewer assumes (L-R P-A I-S) unless the AFNI_ANALYZE_ORIENT environment variable is set.
MRIcro Viewer 1.36 ignores ignores File-to-screen mapping is such that a RPI (R-L, P-A, I-S) file will appear with patient right on screen left, superior at top, and  anterior at top or right depending on view. Files with different ordering of axes will display, but oriented in ways that don't correspond to MRIcro's controls. See screenshots on Orientation page
FSL 3.0 ignores aware of FSL programs do not use the history.orient field. As for pixdims, accordingto Mark Jenkinson: "Negative pixdims are used to determine the Talairach coordinates in fsl programs. They are not used to flip the data order or change the display, only to work out the Talairach (technically the MNI) coordinate in mm."
         

 

Future

Brought to my attention by several correspondents is the NIfTI initiative to define a new descendant of the Analyze format which would fix some of the shortcomings of the existing situation.  Given that the group includes participants from a number of the more active Analyze-format-supporting software development groups, this holds promise that a format spec might result that will be more consistently adhered to.

2003-11-04 Update: More via Darren Weber

Darren posted some additional related info to the FreeSurfer list, of interest to those who really need to understand Analyze data. I feel that DW's work and articles on this subject are the most authoritative available, particularly the notes in his avw_img_read source code that includes email from Analyze support documenting the hist.orient field.

Readers should be aware that his use of data-orientation notation is different from mine -- probably based on our different perceptions of which notations can be relied upon to be understood by others.  I've more or less concluded that the three-letter notation for volume data orientation is sufficiently wobbly that I should always use 6-letter notation (eg: (R-L, P-A, I-S).

Darren's MRI Orientation Notes:
eeg.sourceforge.net/mri_orientation_notes.html
Description of avw_img_read.m

Darren is hosting two pdf docs that are versions of the Mayo Analyze 7.5 format spec. Linked from: Matlab EEG_Toolbox and MRI_Toolbox page, under the "MRI_Toolbox Features" head. You can read these docs in conjunction with the tables above that provide additional notes on the various header fields.

Note 2004-04-15: More on NIfTI Interpretation of

YT on the FreeSurfer list pointed out that the NIfTI 2004-04-15 NIfTI-1 Data Format Extension and Customization spec reports an interpretation of the sagittal flipped value (5) that is at odds with Darren W's research, and the distaillation I provided above.

hist.orient Mayo name Voxel[Index0, Index1, Index2] NIfTI (2004-4-15)
Index0 Index1 Index2 Index0..2
0 (default) transverse unflipped R-L P-A I-S R→L P→A I→S
1 coronal unflipped R-L I-S P-A R→L I→S P→A
2 sagittal unflipped P-A I-S R-L P→A I→S R→L
3 transverse flipped R-L A-P I-S R→L A→P I→S
4 coronal flipped R-L S-I P-A R→L S→I P→A
5 sagittal flipped P-A S-I R-L P→A I→S L→R
Note: Index0 is fastest-varying (innermost-nested) index, Index2 the outermost.
2004-04-15: NIfTI's interpretation of "sagittal flipped" looks off to me. See further notes below.

To resolve this it would be great to see what source NIfTI's interpretation is based upon, and for my part I'll further detail the basis used here.

Darren W at some point received email from support at AnalyzeDirect.com, and includes it in the source code for avw_img_read.m. The salient parts are:

From avw_img_read.m, sections of the email from AnalyzeDirect.com My comments
orient = 2:  The primary orientation of the data on disk is in the sagittal plane relative to the object scanned.  Most commonly, the fastest moving index through the voxels that are part of this sagittal image would span the posterior-anterior extent of the structure imaged, with the next fastest moving index spanning the inferior-superior extent of the structure.  [P-A, I-S, ??]
This 'orient' flag would indicate to Analyze that this data should be placed in the Y-Z plane of the 3D Analyze Coordinate System, with the X dimension being the slice direction. [P-A, I-S, R-L] for orient.hist=2
Orient values 3-5 have the second index reversed in order, so orient.hist=5 says to flip the I-S axis, giving us:
[P-A, S-I, R-L]...
essentially 'flipping' the images relative to what would most likely become the vertical axis of the displayed image. ... with this comment confirming that it's a "vertical" flip that's intended (relative to a viewer), and not an R-L flip.
Left-handed coordinate system
X-Y plane is Transverse
X-Z plane is Coronal
Y-Z plane is Sagittal
X axis runs from patient right (low X) to patient left (high X)
Y axis runs from posterior (low Y) to anterior (high Y)
Z axis runs from inferior (low Z) to superior (high Z)
And for what it's worth, here we have X, Y and Z being used as synonyms for RL, PA and IS spatial axes (and thus not as synonyms for index 0..2).
For the 'sagittal flipped' type, the voxels are stored with
Pixels in 'y' axis (varies fastest) - from patient posterior to Anterior
Rows in   'z' axis                  - from patient superior to Inferior*
Slices in 'x' axis                  - from patient right to Left
And finally, Darren's summary of orient.hist=5

Acknowledgements

Darren Weber: First for researching and debating this problem at length in the past. Extensive posts on FSL and SPM lists. Some of Darren's discoveries are worked into Matlab EEG-MRI Toolbox. The avw_img_read.m file quotes crucial correspondence from Mayo on the meaning of hist.orient.  Second for extensive and patient correspondence on these issues.

Chris Rorden, Author of MRIcro Viewer (and MRI Swiss Army Knife): A number of illuminating emails, explanations and background info.

Steve Smith and Mark Jenkinson of FMRIB for answering a number of questions relating to FSL.

Copyright Acknowledgement

The Analyze 7.5 File Format document contains the following copyright notice regarding the header file format:
ANALYZE TM Header File Format
(c) Copyright, 1986-1995
Biomedical Imaging Resource
Mayo Foundation