nibabel icon indicating copy to clipboard operation
nibabel copied to clipboard

Global option to disable automatic scaling

Open kchawla-pi opened this issue 7 months ago • 1 comments

Nibabel version in use: 5.3.*

Since Nibabel v5.0.0, Nibabel has enable automatic scaling for dtype int. This has created a big problem for us when loading Nifti masks/labels. We have a microservices based platform and Nibabel is imported and used to load, save images at a large number of places. It is proving to be very inconvenient to change the code to do nibabel.Nifti1Image().header.set_slope_inter(1, 0) everywhere necessary.

Currently we have downgraded to Nibabel v4.* to circumvent this problem (thought that is creating other difficulties, mostly due to older bugs, but that is easier for us to handle manually).

It would be most helpful to have a way to set this option globally at the start of a service.

kchawla-pi avatar May 19 '25 17:05 kchawla-pi

Global variables that change the behavior of the library are very dangerous. The package that sets them is not necessarily the only package that uses the API. Perhaps we can discuss the specific problem, and see if there's an alternative usage pattern that will work?

The only situation that should trigger automatic scaling is passing floating point data and saving it as integer. (It's possible, and I'd need to check, that saving 16-bit integers outside the 8-bit range as an 8-bit image would also trigger it.)

If you know you have integer data and just need to retrieve it without converting to float via get_fdata(), np.asanyarray(img.dataobj) will do the job. These arrays can be passed to a new Nifti1Image along with the original header, and no scaling should be triggered.

If you don't know what kind of data you have, you could write a wrapper:

def nonscalingNifti(*args, **kwargs):
    img = nb.Nifti1Image(*args, **kwargs)
    img.header.set_slope_inter(1, 0)
    return img

Those are just some initial thoughts. Happy to talk this through further.

effigies avatar May 25 '25 12:05 effigies