Converting NIfTI to DICOM: A Step-by-Step Guide

Converting NIfTI to DICOM: A Step-by-Step GuideConverting NIfTI (Neuroimaging Informatics Technology Initiative) files to DICOM (Digital Imaging and Communications in Medicine) is a common task when moving neuroimaging data from research environments into clinical workflows or when preparing datasets for systems that require DICOM format. This guide walks through the reasons for conversion, core concepts to understand before converting, several practical methods (command-line tools, Python scripts, and GUI tools), important metadata considerations, QA steps, and tips for automating and integrating conversion into pipelines.


Why convert NIfTI to DICOM?

  • Interoperability: Many clinical systems, PACS (Picture Archiving and Communication Systems), and radiology workflows require DICOM.
  • Metadata requirements: DICOM encodes patient and study metadata in a standardized way needed by clinical systems.
  • Compliance and archiving: DICOM supports long-term archival standards used in hospitals and clinical trials.
  • Visualization and tools: Some viewers and PACS tools require or work better with DICOM inputs.

Key differences between NIfTI and DICOM

  • File model:
    • NIfTI: Typically a single file (or pair .nii/.hdr+.img) representing an entire 3D/4D volume and minimal metadata in a header.
    • DICOM: Series of files where each 2D slice is generally a separate file; extensive standardized metadata stored in DICOM tags.
  • Metadata richness:
    • NIfTI contains voxel dimensions, affine transform, and a few header fields.
    • DICOM contains detailed patient, study, series, acquisition, and device metadata.
  • Use cases:
    • NIfTI: Research, analysis pipelines (FSL, SPM, AFNI).
    • DICOM: Clinical imaging, PACS, regulatory requirements.

Preparations: what you need before converting

  • Source NIfTI files (.nii or .nii.gz). For 4D datasets (e.g., fMRI), decide whether to keep as 4D or split into 3D volumes.
  • Patient/study metadata to populate DICOM tags: patient name, ID, birthdate, sex, study description, accession number, study date/time, referring physician, institution name, and any acquisition-related fields (modality, series description, manufacturer).
  • A mapping plan for spatial orientation and affine transforms: NIfTI uses an affine matrix; DICOM uses Image Position (Patient), Image Orientation (Patient), and Pixel Spacing—these must be consistent.
  • Tools installed (examples below): dcm2niix (for reverse conversion), nibabel (Python), pydicom, dicom-nifti converters like MRIConvert, heudiconv, or commercial solutions.

Methods

Below are common, practical methods for converting NIfTI to DICOM. Choose according to scale, automation needs, and available tooling.


Note: dcm2niix itself is primarily DICOM→NIfTI. For reverse conversion, some projects use MRIConvert or specialized scripts. MRIConvert (older) and other GUI tools can repackage NIfTI to DICOM, but may be less flexible for large automated pipelines.

Pros:

  • GUI options for one-off conversions.
  • Preserves image geometry when supported.

Cons:

  • May require manual metadata entry.
  • Not ideal for large batch jobs.

This is the most flexible approach for precise control over metadata, orientation, and integration into pipelines.

High-level steps:

  1. Load NIfTI with nibabel.
  2. Extract image data and affine; determine slice order and orientation.
  3. Create DICOM metadata template (use an existing DICOM as a template when possible).
  4. For each slice, create a pydicom Dataset, populate required tags, set PixelData, and save as .dcm.

Example Python script (concise, focuses on key steps — adapt metadata as needed):

#!/usr/bin/env python3 # nifti_to_dicom.py import os import uuid import numpy as np import nibabel as nib import pydicom from pydicom.dataset import Dataset, FileDataset from datetime import datetime def nifti_to_dicom(nifti_path, out_dir, template_dcm=None,                    patient_name="Anon", patient_id="0000",                    study_description="Converted from NIfTI"):     img = nib.load(nifti_path)     data = img.get_fdata()     affine = img.affine     os.makedirs(out_dir, exist_ok=True)     # If 4D, handle each volume as a separate series (simple approach)     if data.ndim == 4:         vols = data.shape[3]     else:         vols = 1         data = data[..., np.newaxis]     for vol in range(vols):         series_uid = pydicom.uid.generate_uid()         for z in range(data.shape[2]):             slice_pixels = np.flipud(data[:, :, z, vol]).astype(np.int16)             # Create FileDataset             filename = os.path.join(out_dir, f"vol{vol:03d}_slice{z:03d}.dcm")             file_meta = Dataset()             file_meta.MediaStorageSOPClassUID = pydicom.uid.CTImageStorage             file_meta.MediaStorageSOPInstanceUID = pydicom.uid.generate_uid()             file_meta.ImplementationClassUID = pydicom.uid.PYDICOM_IMPLEMENTATION_UID             ds = FileDataset(filename, {}, file_meta=file_meta, preamble=b"" * 128)             ds.PatientName = patient_name             ds.PatientID = patient_id             ds.StudyInstanceUID = pydicom.uid.generate_uid()             ds.SeriesInstanceUID = series_uid             ds.SOPInstanceUID = file_meta.MediaStorageSOPInstanceUID             ds.Modality = "MR"             ds.SeriesNumber = vol + 1             ds.InstanceNumber = z + 1             ds.ImageType = ["DERIVED", "SECONDARY"]             ds.ContentDate = datetime.now().strftime('%Y%m%d')             ds.ContentTime = datetime.now().strftime('%H%M%S.%f')             # Image pixel data attributes             ds.Rows, ds.Columns = slice_pixels.shape             ds.SamplesPerPixel = 1             ds.PhotometricInterpretation = "MONOCHROME2"             ds.BitsAllocated = 16             ds.BitsStored = 16             ds.HighBit = 15             ds.PixelRepresentation = 1             ds.PixelSpacing = [str(abs(affine[0,0])), str(abs(affine[1,1]))]  # approximate             ds.SliceThickness = str(abs(affine[2,2]))             ds.PixelData = slice_pixels.tobytes()             ds.save_as(filename)     print("Conversion complete:", out_dir) if __name__ == "__main__":     import sys     nifti_to_dicom(sys.argv[1], sys.argv[2]) 

Notes:

  • Use a real DICOM template when possible to populate institution, equipment, and acquisition fields.
  • Properly compute Image Position (Patient) and Image Orientation (Patient) from the affine for correct geometry; above example uses simplified spacing only.
  • Choose appropriate SOP Class UID (MRImageStorage, CTImageStorage, etc.) matching modality.

3) Using heudiconv / dcmstack / dicom-nifti utilities

  • heudiconv: Often used to go from DICOM→BIDS/NIfTI, but scripts and heuristics can be adapted to repackage with metadata.
  • dcmstack: Designed to reconstruct NIfTI from DICOM; reverse workflows exist but require careful metadata handling.
  • Specific projects (e.g., dicomifier) offer utilities to convert NIfTI + metadata structures back into DICOM.

These are generally more advanced and may require customizing a heuristic or metadata mapping.


4) GUI tools and commercial software

  • MRIConvert — older GUI tool capable of NIfTI↔DICOM conversions.
  • 3D Slicer with DICOM export modules — can import NIfTI volumes and export DICOM series, allowing metadata editing.
  • Commercial PACS or vendor tools — often have import wizards to convert research formats to DICOM.

Metadata: what matters and common pitfalls

  • Patient identifiers: Ensure compliance with privacy regulations; de-identify if necessary, but clinical systems need certain identifiers.
  • Study/Series Instance UIDs: Generate persistent UIDs if you want consistent referencing. Use pydicom.uid.generate_uid().
  • Spatial geometry: Compute Image Position (Patient) (0020,0032) and Image Orientation (Patient) (0020,0037) correctly from the NIfTI affine. Mistakes here cause misregistration in PACS/viewers.
  • Pixel representation and scaling: NIfTI uses floating point often; DICOM typically uses integer pixel representations. Apply scaling (Rescale Slope/Intercept) or convert appropriately.
  • Multi-frame vs. single-slice files: Newer DICOM allows multi-frame objects (enhanced MR Image Storage) — easier to store 3D volumes in one file. Older workflows store one slice per file.
  • Time series: For fMRI, map temporal dimension to Per-frame Functional Groups Sequence or split into multiple series depending on destination requirements.

Quality assurance after conversion

  • Visual check: Open converted DICOMs in a DICOM viewer (e.g., OsiriX, RadiAnt, 3D Slicer) and verify orientation, spacing, and anatomical correctness.
  • Metadata verification: Confirm PatientName/ID, StudyDate, SeriesDescription, UID uniqueness, and modality tags.
  • Geometry tests: Compare NIfTI and DICOM-derived coordinates for known fiducials or use registration tools to ensure no flips or swaps occurred.
  • Pixel integrity: Verify intensity histograms and basic statistics between original NIfTI and reconstructed DICOM slices to ensure scaling was correct.

Automating and pipeline integration

  • Use Python scripts with nibabel + pydicom for reproducible batch conversion.
  • Store a DICOM template (anonymized if needed) to copy consistent institutional/equipment tags.
  • Use containerization (Docker) for reproducible environments; include exact versions of nibabel and pydicom.
  • Integrate into BIDS pipelines by exporting metadata sidecars or generating DICOM fields that map to BIDS entities if later re-import is required.

  1. Prepare NIfTI and metadata (patient/study info).
  2. Choose conversion method: Python script (nibabel+pydicom) for automation; 3D Slicer or MRIConvert for quick GUI conversions.
  3. Carefully compute Image Position (Patient) and Orientation from affine.
  4. Convert, choosing appropriate modality and pixel representation.
  5. Run QA checks in a DICOM viewer and verify metadata.
  6. If needed, upload to PACS or archive with proper Study/Series UIDs.

Final tips and resources

  • When possible, retain or reference an original DICOM to copy realistic acquisition metadata.
  • For research-to-clinic transfers, coordinate with the receiving clinical team to confirm required DICOM tags and acceptable formats (single-slice vs. multi-frame).
  • Keep track of UID generation policies if you need persistent identifiers across conversions.

If you want, I can:

  • Provide a complete robust Python script that computes Image Position/Orientation correctly from the NIfTI affine and handles scaling and multi-frame DICOM.
  • Show an example using 3D Slicer to export DICOM with metadata fields filled.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *