Skip to content

Commit 504ced6

Browse files
committed
RF: Add a more resilient method for fetching data dtype
1 parent 4ae3d85 commit 504ced6

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

nibabel/arrayproxy.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -412,3 +412,17 @@ def reshape_dataobj(obj, shape):
412412
"""
413413
return (obj.reshape(shape) if hasattr(obj, 'reshape')
414414
else np.reshape(obj, shape))
415+
416+
417+
def get_obj_dtype(obj):
418+
""" Get the effective dtype of an array-like object """
419+
if is_proxy(obj):
420+
# Read and potentially apply scaling to one value
421+
idx = (0,) * len(obj.shape)
422+
return obj[idx].dtype
423+
elif hasattr(obj, "dtype"):
424+
# Trust the dtype (probably an ndarray)
425+
return obj.dtype
426+
else:
427+
# Coerce; this could be expensive but we don't know what we can do with it
428+
return np.asanyarray(obj).dtype

nibabel/nifti1.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import numpy.linalg as npl
1818
from numpy.compat.py3k import asstr
1919

20+
from .arrayproxy import get_obj_dtype
2021
from .optpkg import optional_package
2122
from .filebasedimages import SerializableImage
2223
from .volumeutils import Recoder, make_dt_codes, endian_codes
@@ -1763,7 +1764,7 @@ def __init__(self, dataobj, affine, header=None,
17631764
# not support 64-bit integer data, so `set_data_dtype(int64)` would
17641765
# already fail.
17651766
danger_dts = (np.dtype("int64"), np.dtype("uint64"))
1766-
if header is None and dtype is None and dataobj.dtype in danger_dts:
1767+
if header is None and dtype is None and get_obj_dtype(dataobj) in danger_dts:
17671768
msg = (f"Image data has type {dataobj.dtype}, which may cause "
17681769
"incompatibilities with other tools. This will error in "
17691770
"future versions of Nibabel. This warning can be silenced "

0 commit comments

Comments
 (0)