NiBabel Documentation

repository·master·Indexed 20 days ago

https://github.com/nipy/nibabel

A Python library providing read and write access to common neuroimaging file formats, exposing image data as NumPy arrays and providing access to file headers. It includes tools for coordinate system transformations (RAS+ convention), affine matrix manipulation, and CLI utilities such as nib-diff, nib-ls, nib-nifti-dx, and tractogram converters (nib-tck2trk, nib-trk2tck).

Tokens
83.4K
Snippets
261
Records
396
Agent score
73%

What's inside NiBabel

  1. Overview of NiBabel

    master

    NiBabel provides read and write access to common neuroimaging file formats. It allows for full or selective access to header information (metadata) and provides image data as NumPy arrays.

    Supported formats include:

    • ANALYZE: plain, SPM99, SPM2, and later
    • GIFTI
    • NIfTI: NIfTI1 and NIfTI2
    • CIFTI-2
    • MINC: MINC1 and MINC2
    • AFNI: BRIK/HEAD
    • ECAT
    • Philips: PAR/REC
    • FreeSurfer: MGH, geometry, annotation, and morphometry files
    • DICOM: Limited support
  2. Overview of NiBabel capabilities

    master

    NiBabel is a Python package designed for efficient neuroimaging data processing. Key features include:

    • Multi-format I/O: Read and write major neuroimaging formats such as NIfTI, ANALYZE, GIFTI, MINC, PAR/REC, and selected DICOM workflows.
    • Rich Header Metadata: Access and edit format-specific metadata through structured headers and validated fields.
    • NumPy-first Data Access: Work with image data as NumPy arrays while preserving the affine and header context required for analysis.
    • Memory-efficient Loading: Use array proxies and lazy loading to inspect large datasets without loading full volumes into memory.
    • Spatial Orientation Utilities: Tools to convert orientations, manipulate affins, and handle voxel-to-world coordinate transformations.
    • Ecosystem Interoperability: Designed to integrate with the scientific Python stack and other neuroimaging libraries.
  3. What is DICOM and how do DICOM files work?

    master

    DICOM (Digital Imaging and Communications in Medicine) is a standard for storing medical data in memory and on disk, and for communicating that data over a network.

    In the context of nibabel, we focus on DICOM files. A DICOM file is essentially a binary dump of the objects that DICOM sends across a network. Specifically, a DICOM file encapsulates a Data Set representing a SOP Instance (Service Object Pair Instance) related to a DICOM IOD (Information Object Definition).

    Key structural concepts:

    • DIMSE (DICOM Message Service Element): The part of a DICOM message that contains information about the service being requested (e.g., C-ECHO or C-STORE).
    • Data Set: The actual data (often medical images) that follows a DIMSE in a network message. In a file, this Data Set is placed after the DICOM File Meta Information.
    • DICOM Elements: The fundamental building blocks that make up both the DIMSE and the subsequent data.
  4. Understand DICOM Attribute Macros

    master

    An Attribute Macro is a named set of attributes that are described in a single table and can be referenced (included) by multiple Modules or other macros. This allows for the reuse of common attribute groups within the DICOM standard.

    When a macro is "Included" in a module, the specific tags and types defined in that macro's table are added to the module's attribute set.

  5. How Nibabel chooses the image affine

    master

    Nibabel determines the primary image .affine by following this priority order (implemented in get_best_affine()):

    1. If sform_code is not 0 ('unknown'), use the sform affine.
    2. Else, if qform_code is not 0 ('unknown'), use the qform affine.
    3. Otherwise, use the fall-back affine.
  6. Conform to the NiBabel Image API

    master

    Every new image format in NiBabel must conform to the standard Image API. To ensure compliance, you should add a test class for your image in nibabel.tests.test_image_api. This allows the core library to interact with your format using a predictable interface.

    When implementing your image, you are responsible for providing three core components:

    1. dataobj: An array or an array proxy (implementing the ArrayProxy API).
    2. affine: A 4x4 array relating image array coordinates to RAS+ world coordinates.
    3. header: A metadata container that implements at least get_data_dtype and get_data_shape.
    class TestMyFormatAPI(LoadImageAPI):
        def loader(self, fname):
            return my_format.load(fname)
    
        example_images = MY_FORMAT_EXAMPLE_IMAGES
  7. Structure of the 4x4 image affine matrix

    master

    The 4x4 image affine matrix $A$ encodes both the linear transformation $M$ (rotation and zoom) and the translation vector $(a, b, c)$.

    If $m_{i,j}$ is the value in row $i$ and column $j$ of the 3x3 matrix $M$, the 4x4 affine matrix is structured as follows:

    $$A = \begin{bmatrix} m_{1,1} & m_{1,2} & m_{1,3} & a \ m_{2,1} & m_{2,2} & m_{2,3} & b \ m_{3,1} & m_{3,2} & m_{3,3} & c \ 0 & 0 & 0 & 1 \end{bmatrix}$$

    In practice, applying the transformation is often computed by breaking it into its components: $$\begin{bmatrix} x \ y \ z \end{bmatrix} = M \begin{bmatrix} i \ j \ k \end{bmatrix} + \begin{bmatrix} a \ b \ c \end{bmatrix}$$ This is mathematically equivalent to the 4x4 homogeneous multiplication as long as the last row is $[0, 0, 0, 1]$.

  8. Calculate the DICOM 2D Affine Matrix

    master

    The 2D affine matrix $A$ maps row ($r$) and column ($c$) indices to patient coordinates $(P_x, P_y, P_z)$.

    To calculate this, first define a flipped orientation matrix $F$ from the 'ImageOrientationPatient' (0020,0037) values $(i_1 .. i_6)$:

    $$F = \begin{bmatrix} i_4 & i_1 \ i_5 & i_2 \ i_6 & i_3 \end{bmatrix}$$

    Where the first column of $F$ is the direction cosine for the row (Y) and the second column is for the column (X). The affine $A$ is then:

    $$\begin{bmatrix} P_x\ P_y\ P_z\ 1 \end{bmatrix} = \begin{bmatrix} F_{11}\Delta{r} & F_{12}\Delta{c} & 0 & S_x \ F_{21}\Delta{r} & F_{22}\Delta{c} & 0 & S_y \ F_{31}\Delta{r} & F_{32}\Delta{c} & 0 & S_z \ 0 & 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} r\ c\ 0\ 1 \end{bmatrix} = A \begin{bmatrix} r\ c\ 0\ 1 \end{bmatrix}$$

    Variables:

    • $S_{xyz}$: Values from Image Position (Patient) (0020,0032).
    • $\Delta{r}$: Row pixel resolution from Pixel Spacing (0028,0030).
    • $\Delta{c}$: Column pixel resolution from Pixel Spacing (0028,0030).
    • $r, c$: Row and column indices (starting at 0).
  9. How Nibabel handles the time axis across different formats

    master

    Nibabel manages the distinction between spatial and temporal axes differently depending on the file format. For many formats (like NIfTI, PAR/REC, ECAT, and MGH), the time axis is conventionally the 4th axis (index 3) in a 4D array.

    However, MINC1 and MINC2 formats typically place the time axis as the first axis. To maintain consistency for users, Nibabel provides mechanisms to identify the time dimension regardless of the underlying format convention.

  10. Understand the structure of a Nibabel image object

    master

    A Nibabel image object is an association of three components:

    1. An N-D array containing the image data.
    2. An affine matrix (4, 4) that maps array coordinates to a RAS+ world coordinate space.
    3. A header containing image metadata.

    You can load an image using nib.load(filename). Once loaded, you can access these components via the .dataobj, .affine, and .header attributes.

    import nibabel as nib
    import os
    
    # Load an image
    img = nib.load('path_to_image.nii.gz')
    
    # Access components
    data_proxy = img.dataobj
    aff_matrix = img.affine
    header = img.header
  11. Reference DICOM Module usage requirements

    master

    When working with DICOM modules, their presence is governed by specific usage requirements defined in the standard. The following abbreviations are used to denote these requirements:

    • M (Mandatory): The module must be present.
    • U (User Option): The module is optional and its presence depends on the user/application.
    • C (Conditional): The module is required only under specific circumstances (e.g., Contrast/bolus is required if contrast media was used in the image).
  12. Understand axis ordering conventions across different image formats

    master

    Nibabel follows a general rule of thumb: when returning an image array, the axes are ordered according to the format's user documentation or the underlying file structure. This means the 'time' or 'volume' axis can appear at different positions depending on the file format:

    • NIfTI: The time axis is the 4th dimension (index 3). For a 4D image, the time axis is the last axis.
    • MGH: The 'frames' (volumes) dimension is the last axis.
    • MINC: The time axis is typically the 1st dimension (index 0), following C-style storage conventions where the first axis is the slowest changing.
    • PAR/REC: Nibabel arranges these with the volume as the 4th and last axis.

    When processing images, always verify the axis order for your specific format to ensure you are correctly identifying slices, time points, or encoding directions (frequency vs. phase).