Skip to content

Wrong header when writing untouched NIfTI file #1484

Description

@fepegar

Description

Header of the written NIfTI file is not valid if no filters are applied to a read NIfTI image. qfac, which is encoded in pixdim[0], should always be -1 or 1, but it's 0.

This was first reported on the Discourse forum.

Steps to Reproduce

  1. Read NIfTI image
  2. Write it
  3. qfacis not valid in the header of the written file

This SimpleITK code should reproduce the issue:

import struct
import numpy as np
import nibabel as nib
import SimpleITK as sitk

def get_qfac(image_path):
    with open(image_path, 'rb') as f:
        fmt = 8 * 'f'
        size = struct.calcsize(fmt)
        f.seek(76)
        chunk = f.read(size)
        pixdim = struct.unpack(fmt, chunk)
    qfac = pixdim[0]
    return qfac

def check_qfac(image_path):
    qfac = get_qfac(image_path)
    if qfac in (-1, 1):
        print('qfac is ok:', qfac)
    else:
        print(f'qfac is {qfac} in {image_path}')

filepath_nib = '/tmp/test_nib.nii'
filepath_itk = '/tmp/test_itk.nii'
array = np.random.rand(10,10,10)
affine = np.eye(4)

print('Written with NiBabel')
nib.Nifti1Image(array, affine).to_filename(filepath_nib)
check_qfac(filepath_nib)

print('\nGetImageFromArray, written with ITK')
im = sitk.GetImageFromArray(array)
sitk.WriteImage(im, filepath_itk)
check_qfac(filepath_itk)

print('\nRead and write with ITK')
im = sitk.ReadImage(filepath_nib)
sitk.WriteImage(im, filepath_itk)
check_qfac(filepath_itk)

Expected behavior

qfac to be -1 or 1.

Actual behavior

qfac is 0.

Written with NiBabel
qfac is ok: 1.0

GetImageFromArray, written with ITK
qfac is ok: 1.0

Read and write with ITK
qfac is 0.0 in /tmp/test_itk.nii

Reproducibility

Always.

Versions

SimpleITK 1.2.4.

Metadata

Metadata

Assignees

No one assigned

    Labels

    status:Use_Milestone_BacklogUse "Backlog" milestone instead of label for issues without a fixed deadlinetype:BugInconsistencies or issues which will cause an incorrect result under some or all circumstances

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions