Skip to content
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

fix imshow when image is RGBA #1906

Merged
merged 7 commits into from
Oct 20, 2021
Merged
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
31 changes: 16 additions & 15 deletions lib/cartopy/mpl/geoaxes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1332,24 +1332,25 @@ def imshow(self, img, *args, **kwargs):
kwargs['alpha'] = alpha

# As a workaround to a matplotlib limitation, turn any images
# which are RGB(A) with a mask into unmasked RGBA images with alpha
# put into the A channel.
# which are masked array RGB(A) into RGBA images

if np.ma.is_masked(img) and len(img.shape) > 2:
# if we don't pop alpha, imshow will apply (erroneously?) a
# 1D alpha to the RGBA array
# kwargs['alpha'] is guaranteed to be either 1D, 2D, or None
alpha = kwargs.pop('alpha')
Copy link
Contributor

Choose a reason for hiding this comment

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

It looks like you are leaving the alpha in the kwargs now, so it will be handled by Matplotlib instead of down below when filling the alpha channel. Are there any weird interactions with showing an RGBA image with an alpha channel and specifying a 2d alpha? I guess I'm not sure what I would even expect in that case.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Good question.

Before this patch, this wasn't a question as alpha kwargs was merged into the data.

import cartopy
import matplotlib.pyplot as plt
import matplotlib
import cartopy.crs as ccrs
import numpy as np
print("matplotlib : ", matplotlib.__version__)

dy, dx = (4,10)

# 2D alpha with stripes
alpha = np.ones((dy, dx))
alpha[:, ::2] = 0

plt.imshow(alpha)
plt.title("2D alpha")
matplotlib :  3.4.3

So with this 2D alpha for example, it should apply stripes :
image

So i checked what happens now that the alpha kwargs is simply passed to matplotlib :

# Create RGBA Image with linspace data and alpha 
RGBA = np.linspace(0, 255*31, dx*dy*4, dtype=np.uint8).reshape((dy, dx, 4))
RGBA[:,:,3]  = np.linspace(0, 255, dx, dtype=np.uint8).reshape(1,dx)

def plot():
    fig  = plt.figure(figsize=(8,3), dpi=120)

    ax1  = fig.add_subplot(1, 3, 1,  projection=ccrs.Orthographic(central_latitude=45))
    ax1.set_title("Orthographic axis")
    ax2  = fig.add_subplot(1, 3, 2,  projection=ccrs.PlateCarree())
    ax2.set_title("PlateCarree axis")
    ax3  = fig.add_subplot(1, 3, 3)
    ax3.set_title("no projection axis")
    return fig, ax1, ax2, ax3

fig, ax1, ax2, ax3 = plot()

ax1.imshow(RGBA, alpha=alpha, transform=ccrs.PlateCarree())
ax2.imshow(RGBA, alpha=alpha, transform=ccrs.PlateCarree())
ax3.imshow(RGBA, alpha=alpha, )
   
fig.suptitle("RGBA u1 data in PlateCarre projection with alpha 2D")
matplotlib :  3.4.3

image

I don't see the alpha stripes.

So it looks like the 2D alpha kwargs has no impacts, as if no alpha kwargs was used.
It does nothing with cartopy, but with matplotlib too (so at least the cartopy behavior mimic matplotlib behavior?)

Which is weird because in the matplotlib documentation from imshow it is clearly stated that "If alpha is an array, the alpha blending values are applied pixel by pixel, and alpha must have the same shape as X".

SO it doesn't nothing, so do matplotlib.

Did i something wrong with matplotlib, or should i raise a ticket ?

(for info, the "problem" persist with RGBA u1 and with RGBA f4 too)

Copy link
Contributor

Choose a reason for hiding this comment

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

Actually, before this patch I think the alpha did get converted to the data array as you mentioned (striped alpha). Which is actually not what Matplotlib does as you mention. So, we were actually deviating from Matplotlib there.

A quick look shows that the alpha 2d array only works with colormapped values on Matplotlib standard Axes. It does not apply to RGB or RGBA images. I think I agree with what Matplotlib is doing there, and I like what you've done here to force us to be more consistent with that. If someone wants a 2d alpha array, they should not be sending in RGB(A) data. (I guess RGB is a bit questionable, but I think it makes sense to keep those consistent)

In summary, I agree with what you've done here.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ok thanks

old_img = img[:, :, 0:3]
img = np.zeros(img.shape[:2] + (4, ), dtype=img.dtype)
img[:, :, 0:3] = old_img
# Put an alpha channel in if the image was masked.
if not np.any(alpha):
alpha = 1
img[:, :, 3] = np.ma.filled(alpha, fill_value=0) * \
(~np.any(old_img.mask, axis=2))
if img.dtype.kind == 'u':

# transform RGB(A) into RGBA
old_img = img
img = np.ones(old_img.shape[:2] + (4, ),
dtype=old_img.dtype)
img[:, :, :3] = old_img[:, :, :3]

# if img is RGBA, save alpha channel
if old_img.shape[-1] == 4:
img[:, :, 3] = old_img[:, :, 3]
elif img.dtype.kind == 'u':
img[:, :, 3] *= 255

# apply the mask to the A channel
img[np.any(old_img[:, :, :3].mask, axis=2), 3] = 0

result = super().imshow(img, *args, extent=extent, **kwargs)

return result
Expand Down
16 changes: 16 additions & 0 deletions lib/cartopy/tests/mpl/test_images.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,22 @@ def test_imshow_rgba():
assert sum(img.get_array().data[:, 0, 3]) == 0


def test_imshow_rgba_alpha():
# test that alpha channel from RGBA is not skipped
dy, dx = (3, 4)

ax = plt.axes(projection=ccrs.Orthographic(-120, 45))

# Create RGBA Image with random data and linspace alpha
RGBA = np.linspace(0, 255*31, dx*dy*4, dtype=np.uint8).reshape((dy, dx, 4))

alpha = np.array([0, 85, 170, 255])
RGBA[:, :, 3] = alpha

img = ax.imshow(RGBA, transform=ccrs.PlateCarree())
assert np.all(np.unique(img.get_array().data[:, :, 3]) == alpha)


def test_imshow_rgb():
# tests that the alpha of a RGB array passed to imshow is set to 0
# instead of masked
Expand Down