nifti-reader-js

repository·master·Indexed 40 days ago

https://github.com/rii-mango/nifti-reader-js

A JavaScript library for reading NIfTI-1 and NIfTI-2 file formats, supporting both compressed (.nii.gz) and uncompressed (.nii) files. It provides tools to parse headers, extract image voxel data, and manage NIfTI extensions in the browser or Node.js. Version 0.8.0 includes classes for NIFTI1 and NIFTI2 headers, as well as utilities for decompression and coordinate transformation.

Tokens
4K
Snippets
14
Records
22
Agent score
99%

What's inside nifti-reader-js

  1. Read NIfTI files from an ArrayBuffer

    master

    To read a NIfTI file, you must first check if the data is compressed (e.g., .nii.gz) and decompress it if necessary. Once uncompressed, you can verify if it is a valid NIfTI format, read the header, and then extract the image data. You can also optionally read extension data if the header contains extensions.

    Workflow:

    1. Check compression with isCompressed(data).
    2. Decompress with decompress(data) if needed.
    3. Verify NIfTI format with isNIFTI(data).
    4. Parse header with readHeader(data).
    5. Parse image data with readImage(niftiHeader, data).
    6. (Optional) Parse extensions with readExtensionData(niftiHeader, data) if hasExtension(niftiHeader) is true.
    var data = // an ArrayBuffer
    var niftiHeader = null,
        niftiImage = null,
        niftiExt = null;
    
    if (nifti.isCompressed(data)) {
        data = nifti.decompress(data);
    }
    
    if (nifti.isNIFTI(data)) {
        niftiHeader = nifti.readHeader(data);
        console.log(niftiHeader.toFormattedString());
        niftiImage = nifti.readImage(niftiHeader, data);
        
        if (nifti.hasExtension(niftiHeader)) {
            niftiExt = nifti.readExtensionData(niftiHeader, data);
        }
    }
  2. Manage NIfTI extensions

    master

    NIfTI-1 files can contain extensions. You can manage these using the NIFTI1 instance methods:

    • addExtension(extension: NIFTIEXTENSION, index = -1): Adds a new extension. If index is -1, it is appended to the end. This method automatically updates the vox_offset to account for the new extension's size.
    • removeExtension(index: number): Removes an extension at the specified index and updates the vox_offset accordingly.
    • getExtensionLocation(): Returns the byte index where extensions begin (constant: NIFTI1.MAGIC_COOKIE + 4).
  3. Use the NIFTI2 class for NIfTI-2 files

    master

    The NIFTI2 class is used to represent and manipulate NIfTI-2 header data. It provides methods to read header data from an ArrayBuffer, convert the header back into an ArrayBuffer, and inspect various image properties like dimensions, voxel sizes, and affine transformations.

    Key properties include:

    • dims: Image dimensions (up to 8).
    • pixDims: Voxel dimensions (up to 8).
    • datatypeCode: The NIfTI datatype code.
    • vox_offset: The byte offset to the start of the image data.
    • affine: A 4x4 matrix representing the transformation.
    • extensions: An array of NIFTIEXTENSION objects.
    • littleEndian: Boolean indicating the endianness of the file.
    import { NIFTI2 } from './nifti2.js';
    
    const nifti2 = new NIFTI2();
    // Assuming 'buffer' is an ArrayBuffer from a NIfTI-2 file
    nifti2.readHeader(buffer);
    
    console.log(nifti2.dims);
    console.log(nifti2.affine);
  4. Read NIfTI image data

    master

    Once you have a header object, use readImage to extract the actual voxel data from the ArrayBuffer.

    readImage(header, data): Calculates the image size based on dimensions (dims), time dimension (dims[4]), statistical dimension (dims[5]), and bits per voxel, then returns a slice of the data buffer starting at header.vox_offset.

    import { readHeader, readImage } from 'nifti-reader-js';
    
    const header = readHeader(arrayBuffer);
    if (header) {
      const imageData = readImage(header, arrayBuffer);
      // Use imageData...
    }
  5. Read NIfTI headers

    master

    To extract metadata from a NIfTI file, use readHeader or readHeaderAsync. These functions automatically handle decompression if the input data is compressed.

    • readHeader(data, isHdrImgPairOK): Synchronously reads the header and returns a NIFTI1 or NIFTI2 object.
    • readHeaderAsync(data, isHdrImgPairOK): Asynchronously reads the header. This is recommended for compressed files to avoid blocking the main thread. It uses decompressHeaderAsync internally to efficiently read only the necessary portion of the file to identify the header and its extensions.
    import { readHeaderAsync } from 'nifti-reader-js';
    
    const header = await readHeaderAsync(arrayBuffer);
    console.log(header.dims);
  6. Read a NIfTI-1 header from an ArrayBuffer

    master

    To parse a NIfTI-1 header, instantiate a NIFTI1 object and call its readHeader method, passing in an ArrayBuffer containing the header data. The method automatically detects endianness and validates the NIfTI magic cookie. If the data is not a valid NIfTI file, it will throw an error.

    import { NIFTI1 } from './nifti1.js';
    
    const header = new NIFTI1();
    // data is an ArrayBuffer from a file or network request
    header.readHeader(data);
    
    // Access properties after reading
    console.log('Dimensions:', header.dims);
    console.log('Voxel Dims:', header.pixDims);
    console.log('Datatype Code:', header.datatypeCode);
  7. Access NIfTI extensions

    master

    NIfTI files can contain metadata extensions. Use these functions to access them:

    • hasExtension(header): Returns true if the header contains an extension.
    • readExtension(header, data): Returns the raw extension data, including the extension header.
    • readExtensionData(header, data): Returns only the extension data (skipping the extension header and metadata).
  8. Detect NIfTI file types

    master

    Use the following functions to determine if an ArrayBuffer contains a NIfTI-1, NIfTI-2, or general NIfTI header. The isHdrImgPairOK option can be set to true if you are handling a split header/image pair.

    • isNIFTI(data, isHdrImgPairOK): Returns true if the data is either NIfTI-1 or NIfTI-2.
    • isNIFTI1(data, isHdrImgPairOK): Returns true if the data is a NIfTI-1 header.
    • isNIFTI2(data, isHdrImgPairOK): Returns true if the data is a NIfTI-2 header.
  9. Export NIfTI-1 header to ArrayBuffer

    master

    To serialize a NIFTI1 instance back into a binary format, use the toArrayBuffer method.

    • toArrayBuffer(includeExtensions = false): Returns an ArrayBuffer representing the header. If includeExtensions is set to true, the resulting buffer will include the bytes for all extensions currently stored in the extensions array.
    const buffer = header.toArrayBuffer(true);
    // 'buffer' is now a ready-to-use ArrayBuffer including extensions
  10. Decompress NIfTI data

    master

    If your NIfTI file is GZIP compressed, you can decompress it using these functions:

    • isCompressed(data): Checks if the ArrayBuffer is GZIP compressed.
    • decompress(data): Synchronously decompresses the ArrayBuffer using fflate.
    • decompressAsync(data): Asynchronously decompresses the ArrayBuffer using the DecompressionStream API.