Skip to content

Commit

Permalink
Merge pull request #2468 from bmorris3/cmap-bad-preserve-alpha
Browse files Browse the repository at this point in the history
Preserve alpha while compositing with cmap.set_bad
  • Loading branch information
astrofrog authored Feb 28, 2024
2 parents 5f38baf + 822a9dc commit 785e29b
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions glue/viewers/image/composite_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ def __init__(self, **kwargs):

self._first = True
self._mode = 'color'
self._allow_bad_alpha = False

@property
def mode(self):
Expand Down Expand Up @@ -146,10 +147,16 @@ def __call__(self, bounds=None):
# ensure "bad" values have the same alpha as the
# rest of the layer:
if hasattr(layer['cmap'], 'get_bad'):
bad_color = layer['cmap'].get_bad().tolist()[:3]
layer_cmap = layer['cmap'].with_extremes(
bad=bad_color + [layer['alpha']]
)
bad_rgba = layer['cmap'].get_bad().tolist()
bad_color = bad_rgba[:3]
bad_alpha = bad_rgba[3:]

if self._allow_bad_alpha:
bad_rgba = bad_color + bad_alpha
else:
bad_rgba = bad_color + [layer['alpha']]

layer_cmap = layer['cmap'].with_extremes(bad=bad_rgba)
else:
layer_cmap = layer['cmap']

Expand All @@ -162,8 +169,7 @@ def __call__(self, bounds=None):
# Check what the smallest colormap alpha value for this layer is
# - if it is 1 then this colormap does not change transparency,
# and this allows us to speed things up a little.
if layer_cmap(CMAP_SAMPLING)[:, 3].min() == 1:

if layer_cmap(CMAP_SAMPLING)[:, 3].min() == 1 and (not self._allow_bad_alpha or bad_alpha == 1):
if layer['alpha'] == 1:
img[...] = 0
else:
Expand All @@ -175,6 +181,10 @@ def __call__(self, bounds=None):
# Use traditional alpha compositing
alpha_plane = layer['alpha'] * plane[:, :, 3]

if self._allow_bad_alpha:
# ensure "bad" alpha is preserved:
alpha_plane[~np.isfinite(data)] *= bad_alpha

plane[:, :, 0] = plane[:, :, 0] * alpha_plane
plane[:, :, 1] = plane[:, :, 1] * alpha_plane
plane[:, :, 2] = plane[:, :, 2] * alpha_plane
Expand Down

0 comments on commit 785e29b

Please sign in to comment.