8000 Clip RGB data to vaild range in Axes.imshow · matplotlib/matplotlib@1d45a59 · GitHub
[go: up one dir, main page]

Skip to content

Commit 1d45a59

Browse files
committed
Clip RGB data to vaild range in Axes.imshow
1 parent 12a3b4f commit 1d45a59

File tree

6 files changed

+51
-7
lines changed

6 files changed

+51
-7
lines changed

doc/users/credits.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,7 @@ Yu Feng,
386386
Yunfei Yang,
387387
Yuri D'Elia,
388388
Yuval Langer,
389+
Zac Hatfield-Dodds,
389390
Zach Pincus,
390391
Zair Mubashar,
391392
alex,
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
`Axes.imshow` clips RGB values to the valid range
2+
-------------------------------------------------
3+
4+
When `Axes.imshow` is passed an RGB or RGBA value with out-of-range
5+
values, it now issues a warning and clips them to the valid range.
6+
The old behaviour, wrapping back in to the range, often hid outliers
7+
and made interpreting RGB images unreliable.

lib/matplotlib/axes/_axes.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5239,10 +5239,14 @@ def imshow(self, X, cmap=None, norm=None, aspect=None,
52395239
- MxNx3 -- RGB (float or uint8)
52405240
- MxNx4 -- RGBA (float or uint8)
52415241
5242-
The value for each component of MxNx3 and MxNx4 float arrays
5243-
should be in the range 0.0 to 1.0. MxN arrays are mapped
5244-
to colors based on the `norm` (mapping scalar to scalar)
5245-
and the `cmap` (mapping the normed scalar to a color).
5242+
MxN arrays are mapped to colors based on the `norm` (mapping
5243+
scalar to scalar) and the `cmap` (mapping the normed scalar to
5244+
a color).
5245+
5246+
Elements of RGB and RGBA arrays represent pixels of an MxN image.
5247+
All values should be in the range [0 .. 1] for floats or
5248+
[0 .. 255] for integers. Out-of-range values will be clipped to
5249+
these bounds.
52465250
52475251
cmap : `~matplotlib.colors.Colormap`, optional, default: None
52485252
If None, default to rc `image.cmap` value. `cmap` is ignored
@@ -5284,7 +5288,8 @@ def imshow(self, X, cmap=None, norm=None, aspect=None,
52845288
settings for `vmin` and `vmax` will be ignored.
52855289
52865290
alpha : scalar, optional, default: None
5287-
The alpha blending value, between 0 (transparent) and 1 (opaque)
5291+
The alpha blending value, between 0 (transparent) and 1 (opaque).
5292+
The ``alpha`` argument is ignored for RGBA input data.
52885293
52895294
origin : ['upper' | 'lower'], optional, default: None
52905295
Place the [0,0] index of the array in the upper left or lower left

lib/matplotlib/cm.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ def to_rgba(self, x, alpha=None, bytes=False, norm=True):
259259
xx = (xx * 255).astype(np.uint8)
260260
elif xx.dtype == np.uint8:
261261
if not bytes:
262-
xx = xx.astype(float) / 255
262+
xx = xx.astype(np.float32) / 255
263263
else:
264264
raise ValueError("Image RGB array must be uint8 or "
265265
"floating point; found %s" % xx.dtype)

lib/matplotlib/image.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
from math import ceil
1515
import os
16+
import logging
1617

1718
import numpy as np
1819

@@ -34,6 +35,8 @@
3435
from matplotlib.transforms import (Affine2D, BboxBase, Bbox, BboxTransform,
3536
IdentityTransform, TransformedBbox)
3637

38+
_log = logging.getLogger(__name__)
39+
3740
# map interpolation strings to module constants
3841
_interpd_ = {
3942
'none': _image.NEAREST, # fall back to nearest when not supported
@@ -610,6 +613,23 @@ def set_data(self, A):
610613
or self._A.ndim == 3 and self._A.shape[-1] in [3, 4]):
611614
raise TypeError("Invalid dimensions for image data")
612615

616+
if self._A.ndim == 3:
617+
# If the input data has values outside the valid range (after
618+
# normalisation), we issue a warning and then clip X to the bounds
619+
# - otherwise casting wraps extreme values, hiding outliers and
620+
# making reliable interpretation impossible.
621+
high = 255 if np.issubdtype(self._A.dtype, np.integer) else 1
622+
if self._A.min() < 0 or high < self._A.max():
623+
_log.warning(
624+
'Clipping input data to the valid range for imshow with '
625+
'RGB data ([0..1] for floats or [0..255] for integers).'
626+
)
627+
self._A = np.clip(self._A, 0, high)
628+
# Cast unsupported integer types to uint8
629+
if self._A.dtype != np.uint8 and np.issubdtype(self._A.dtype,
630+
np.integer):
631+
self._A = self._A.astype(np.uint8)
632+
613633
self._imcache = None
614634
self._rgbacache = None
615635
self.stale = True

lib/matplotlib/tests/test_image.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -602,7 +602,7 @@ def test_minimized_rasterized():
602602
def test_load_from_url():
603603
req = six.moves.urllib.request.urlopen(
604604
"http://matplotlib.org/_static/logo_sidebar_horiz.png")
605-
Z = plt.imread(req)
605+
plt.imread(req)
606606

607607

608608
@image_comparison(baseline_images=['log_scale_image'],
@@ -795,6 +795,17 @@ def test_imshow_no_warn_invalid():
795795
assert len(warns) == 0
796796

797797

798+
@pytest.mark.parametrize('as_float', [True, False])
799+
def test_imshow_logs_when_clipping_invalid_rgb(as_float, caplog):
800+
arr = np.arange(300).reshape((10, 10, 3))
801+
if as_float:
802+
arr = arr / 255
803+
fig = plt.figure()
804+
ax = fig.add_subplot(111)
805+
ax.imshow(arr)
806+
assert 'Clipping input data to the valid range for imshow' in caplog.text
807+
808+
798809
@image_comparison(baseline_images=['imshow_flatfield'],
799810
remove_text=True, style='mpl20',
800811
extensions=['png'])

0 commit comments

Comments
 (0)
0