InsightSoftwareConsortium / InsightSoftwareConsortium/ITK
Wrong header when writing untouched NIfTI file
- Dominant language
- C++
- Stars
- 1.7k
- Forks
- 748
- Avg merge
- 1d 1h
- Merged PRs (30d)
- 64
Description
### 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](https://discourse.itk.org/t/simpleitk-writing-nifti-with-invalid-header/2498).
### Steps to Reproduce
1. Read NIfTI image
2. Write it
3. `qfac`is not valid in the header of the written file
This `SimpleITK` code should reproduce the issue:
```python
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`.
```none
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`.
Contributor guide
Assessment
This issue has not been assessed yet.