[Neuroimaging] [nibabel] reading corrupt *.nii.gz files

Matthew Brett matthew.brett at gmail.com
Wed Sep 30 21:29:58 CEST 2015

Hi Dimitri,

On Wed, Sep 30, 2015 at 6:35 AM, Dimitri Papadopoulos Orfanos
<dimitri.papadopoulos at cea.fr> wrote:
> Dear all,
> The following code emits an exception:
>     import nibabel
>     NIFTI_FILE = 'FLAIR.nii.gz'
>     img = nibabel.load(NIFTI_FILE)
>     import nibabel
>     try:
>         data = img.get_data()
>     except zlib.error as err:
>         print(err)
> The outptut is:
>     Error -3 while decompressing: invalid code lengths set
> The reason is that NIfTI file FLAIR.nii.gz is corrupted:
>     $ gunzip
>     gzip: FLAIR.nii.gz: invalid compressed data--format violated
>     $
> While in many such situations throwing an exception is the right thing
> to do, there are cases where I would like to override the error and read
> whatever data is available. For example it could be useful to be able to
> display the image the same way FSLView does (see
> http://www.pictureshack.us/images/10675_FLAIR.png). Also please note
> that PyNIfTI does read the corrupted file without raising an error.
> We have hundreds such corrupted FLAIR files, probably due to a bug in
> older versions of dcm2nii.
> So here are my questions:
> * Shouldn't ninabel catch the zlib exception and raise its own (more
> user-friendly) exception?

Would the friendly error be much different from the unfriendly one
though?  I guess it would just be something like 'Error reading
compressed image data : Error -3 while decompressing: invalid code
lengths set' ?

> * Is there a way to avoid the exception and read whatever data is
> available in the corrupted file?

Not at the moment.

> * If there is currently no way to avoid the exception, would it be
> acceptable to add such an option to nibabel?

Yes, sure.  I don't think it should be the default, but as an extra
flag to load, it would be fine.  Have a look for the implementation of
the ``mmap`` option for the general idea:


See you,


More information about the Neuroimaging mailing list