Skip to content

Commit

Permalink
Use more complete list of _integer_types for convert (#7392)
Browse files Browse the repository at this point in the history
These were removed in d1712b5 with the
thought that using explicit dtypes with the bit size in their name would
be enough to cover all cases.

Turns out that NumPy's dtype system is a bit more complex than that and
for NumPy <2.0 there are cases where dtype.type is np.ulonglong (see
test). So let's be cautious and add back all the "aliases". Fixes [1]

[1] https://www.github.com/scikit-image/scikit-image/issues/7385
  • Loading branch information
lagru committed Apr 12, 2024
1 parent b7434c8 commit 55998da
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
12 changes: 12 additions & 0 deletions skimage/util/dtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,29 @@
'dtype_limits',
]

# Some of these may or may not be aliases depending on architecture & platform
_integer_types = (
np.int8,
np.byte,
np.int16,
np.short,
np.int32,
np.int64,
np.longlong,
np.int_,
np.intp,
np.intc,
int,
np.uint8,
np.ubyte,
np.uint16,
np.ushort,
np.uint32,
np.uint64,
np.ulonglong,
np.uint,
np.uintp,
np.uintc,
)
_integer_ranges = {t: (np.iinfo(t).min, np.iinfo(t).max) for t in _integer_types}
dtype_range = {
Expand Down
12 changes: 12 additions & 0 deletions skimage/util/tests/test_dtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,15 @@ def test_int_to_float():

assert_equal(floats.max(), 1)
assert_equal(floats.min(), -1)


def test_img_as_ubyte_supports_npulonglong():
# Pre NumPy <2.0.0, `data_scaled.dtype.type` is `np.ulonglong` instead of
# np.uint64 as one might expect. This caused issues with `img_as_ubyte` due
# to `np.ulonglong` missing from `skimage.util.dtype._integer_types`.
# This doesn't seem to be an issue for NumPy >=2.0.0.
# https://github.com/scikit-image/scikit-image/issues/7385
data = np.arange(50, dtype=np.uint64)
data_scaled = data * 256 ** (data.dtype.itemsize - 1)
result = img_as_ubyte(data_scaled)
assert result.dtype == np.uint8

0 comments on commit 55998da

Please sign in to comment.