Skip to content

FIX: also exclude np.nan in RGB(A) in color mapping #27303

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion lib/matplotlib/cm.py
Original file line number Diff line number Diff line change
Expand Up @@ -487,9 +487,12 @@ def to_rgba(self, x, alpha=None, bytes=False, norm=True):
else:
raise ValueError("Third dimension must be 3 or 4")
if xx.dtype.kind == 'f':
if norm and (xx.max() > 1 or xx.min() < 0):
if norm and (
np.any(np.isnan(xx)) or (xx.max() > 1 or xx.min() < 0)
):
Copy link
Contributor

@anntzer anntzer Nov 10, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rewrite as
if not (xx.min() >= 0 and xx.max() <= 1) (with a comment explaining that this form also excludes nans) and no extra nan checking to save a tiny bit of performance?

raise ValueError("Floating point image RGB values "
"must be in the 0..1 range.")

if bytes:
xx = (xx * 255).astype(np.uint8)
elif xx.dtype == np.uint8:
Expand Down
17 changes: 17 additions & 0 deletions lib/matplotlib/tests/test_colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -1400,6 +1400,23 @@ def test_scalarmappable_to_rgba(bytes):
np.testing.assert_array_equal(sm.to_rgba(xm[..., :3], bytes=bytes), expected)


@pytest.mark.parametrize("inp", (
[[[2, .5, 1], [.5, .5, .5]]],
[[[np.nan, .5, 1], [.5, .5, .5]]],
[[[-1, .5, 1], [.5, .5, .5]]],
[[[np.inf, .5, 1], [.5, .5, .5]]],
[[[-np.inf, .5, 1], [.5, .5, .5]]]
)
)
def test_scalarmappable_to_rgba_invalid(inp):
sm = cm.ScalarMappable()
with pytest.raises(
ValueError,
match="Floating point image RGB values must be in the 0..1 range."
):
sm.to_rgba(np.asarray(inp))


def test_failed_conversions():
with pytest.raises(ValueError):
mcolors.to_rgba('5')
Expand Down