nipy / nibabel

Python package to access a cacophony of neuro-imaging file formats
http://nipy.org/nibabel/
Other
649 stars 258 forks source link

Unresolved attribute reference warning in Pycharm #1246

Closed pwrightkcl closed 1 year ago

pwrightkcl commented 1 year ago

I am using nibabel 5.1.0 in a script in Pycharm, and I'm getting highlighted warnings in code like this:

import nibabel as nib

image = nib.load('my_image.nii')
voxel_dims = image.header.get_data_shape()
Y = image.get_fdata()

# Do something to Y

new_image = nib.Nifti1Image(Y, image.affine, image.header)

The script seems to run OK, so it seems like an issue with Pycharm's checking. Looking at filebasedimages.py I don't see the get_data_shape method etc. so I guess those must be added when a child class specific to NIfTI images comes into play.

I don't know enough about Python namespaces and Pycharm's code checking, so I'm just going to leave this here for others to decide whether this requires any action on the nibabel side. If someone feels like dropping an educational reply, that would be an unexpected bonus.

effigies commented 1 year ago

Does #1220 help?

pwrightkcl commented 1 year ago

Thanks, @effigies, that is informative. I can specify the type of my image object and clear the warnings as you describe in #1220.

image2 = nib.Nifti1Image.from_filename('my_image.nii')
voxel_dims2 = image2.header.get_data_shape()
Y2 = image2.get_fdata()
new_image2 = nib.Nifti1Image(Y, image2.affine, image.header)

I still get a warning for get_data_shape because the header is still default typed as FileBasedHeader. I can get that to go away as follows:

image3 = nib.Nifti1Image.from_filename('my_image.nii')
header3 = nib.Nifti1Header.from_fileobj(image3)
voxel_dims3 = header3.get_data_shape()

Thanks for the explanation.

effigies commented 1 year ago

I still get a warning for get_data_shape because the header is still default typed as FileBasedHeader

This seems like a bug in pycharm. It is detected as a nifti header by mypy. Happy to fix up the annotation to work with more tools, but I'll need advice from those familiar with them.

effigies commented 1 year ago

Also, if you just need the shape, img.shape ought to do the trick.