Thanks to visit codestin.com
Credit goes to github.com

Skip to content

issue with transparency in imshow #16730

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
pink2289 opened this issue Mar 11, 2020 · 5 comments
Closed

issue with transparency in imshow #16730

pink2289 opened this issue Mar 11, 2020 · 5 comments
Labels
Community support Users in need of help.

Comments

@pink2289
Copy link

pink2289 commented Mar 11, 2020

Bug report

Hi, I am trying to understand the following example on how to provide an array-like alpha in imshow.

https://matplotlib.org/3.2.0/gallery/images_contours_and_fields/image_transparency_blend.html

However, the exact same script gives me following errors. What is the source of this bug?

Bug summary

ValueError: operands could not be broadcast together with shapes (218,218) (100,100)

Code for reproduction


def normal_pdf(x, mean, var):
    return np.exp(-(x - mean)**2 / (2*var))

# Generate the space in which the blobs will live
xmin, xmax, ymin, ymax = (0, 100, 0, 100)
n_bins = 100
xx = np.linspace(xmin, xmax, n_bins)
yy = np.linspace(ymin, ymax, n_bins)

# Generate the blobs. The range of the values is roughly -.0002 to .0002
means_high = [20, 50]
means_low = [50, 60]
var = [150, 200]

gauss_x_high = normal_pdf(xx, means_high[0], var[0])
gauss_y_high = normal_pdf(yy, means_high[1], var[0])

gauss_x_low = normal_pdf(xx, means_low[0], var[1])
gauss_y_low = normal_pdf(yy, means_low[1], var[1])

weights = (np.outer(gauss_y_high, gauss_x_high) - np.outer(gauss_y_low, gauss_x_low))

# We'll also create a grey background into which the pixels will fade
#greys = np.full((*weights.shape, 3), 70, dtype=np.uint8)

# First we'll plot these blobs using ``imshow`` without transparency.
vmax = np.abs(weights).max()
imshow_kwargs = {
    'vmax': vmax,
    'vmin': -vmax,
    'cmap': 'RdYlBu',
    'extent': (xmin, xmax, ymin, ymax),
}

fig, ax = plt.subplots()
#ax.imshow(greys)
ax.imshow(weights, **imshow_kwargs)
ax.set_axis_off()

# Create an alpha channel of linearly increasing values moving to the right.
alphas = np.ones(weights.shape)
alphas[:, 30:] = np.linspace(1, 0, 70)

# Create the figure and image
# Note that the absolute values may be slightly different
fig, ax = plt.subplots()
#ax.imshow(greys)
ax.imshow(weights, alpha=alphas, **imshow_kwargs)
ax.set_axis_off()

Actual outcome

# If applicable, paste the console output here
#
#
Error in callback <function post_execute at 0x7f4972d48578> (for post_execute):
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/pyplot.pyc in post_execute()
    147             def post_execute():
    148                 if matplotlib.is_interactive():
--> 149                     draw_all()
    150 
    151             # IPython >= 2

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/_pylab_helpers.pyc in draw_all(cls, force)
    134         for f_mgr in cls.get_all_fig_managers():
    135             if force or f_mgr.canvas.figure.stale:
--> 136                 f_mgr.canvas.draw_idle()
    137 
    138 atexit.register(Gcf.destroy_all)

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/backend_bases.pyc in draw_idle(self, *args, **kwargs)
   2053         if not self._is_idle_drawing:
   2054             with self._idle_draw_cntx():
-> 2055                 self.draw(*args, **kwargs)
   2056 
   2057     def draw_cursor(self, event):

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in draw(self)
    435             # if toolbar:
    436             #     toolbar.set_cursor(cursors.WAIT)
--> 437             self.figure.draw(self.renderer)
    438             # A GUI class may be need to update a window using this draw, so
    439             # don't forget to call the superclass.

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/figure.pyc in draw(self, renderer)
   1491 
   1492             mimage._draw_list_compositing_images(
-> 1493                 renderer, self, artists, self.suppressComposite)
   1494 
   1495             renderer.close_group('figure')

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/image.pyc in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    139     if not_composite or not has_images:
    140         for a in artists:
--> 141             a.draw(renderer)
    142     else:
    143         # Composite any adjacent images together

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/axes/_base.pyc in draw(self, renderer, inframe)
   2633             renderer.stop_rasterizing()
   2634 
-> 2635         mimage._draw_list_compositing_images(renderer, self, artists)
   2636 
   2637         renderer.close_group('axes')

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/image.pyc in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    139     if not_composite or not has_images:
    140         for a in artists:
--> 141             a.draw(renderer)
    142     else:
    143         # Composite any adjacent images together

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/image.pyc in draw(self, renderer, *args, **kwargs)
    592         else:
    593             im, l, b, trans = self.make_image(
--> 594                 renderer, renderer.get_image_magnification())
    595             if im is not None:
    596                 renderer.draw_image(gc, l, b, im)

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/image.pyc in make_image(self, renderer, magnification, unsampled)
    840         return self._make_image(
    841             self._A, bbox, transformed_bbox, self.axes.bbox, magnification,
--> 842             unsampled=unsampled)
    843 
    844     def _check_unsampled_image(self, renderer):

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/image.pyc in _make_image(self, A, in_bbox, out_bbox, clip_bbox, magnification, unsampled, round_to_pixel_border)
    520                 alpha_channel = output[:, :, 3]
    521                 alpha_channel[:] = np.asarray(
--> 522                     np.asarray(alpha_channel, np.float32) * out_alpha * alpha,
    523                     np.uint8)
    524 

ValueError: operands could not be broadcast together with shapes (218,218) (100,100) 

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/xxx/anaconda2/lib/python2.7/site-packages/IPython/core/formatters.pyc in __call__(self, obj)
    332                 pass
    333             else:
--> 334                 return printer(obj)
    335             # Finally look for special method names
    336             method = get_real_method(obj, self.print_method)

/xxx/anaconda2/lib/python2.7/site-packages/IPython/core/pylabtools.pyc in <lambda>(fig)
    245 
    246     if 'png' in formats:
--> 247         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
    248     if 'retina' in formats or 'png2x' in formats:
    249         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

/xxx/anaconda2/lib/python2.7/site-packages/IPython/core/pylabtools.pyc in print_figure(fig, fmt, bbox_inches, **kwargs)
    129 
    130     bytes_io = BytesIO()
--> 131     fig.canvas.print_figure(bytes_io, **kw)
    132     data = bytes_io.getvalue()
    133     if fmt == 'svg':

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/backend_bases.pyc in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
   2210                     orientation=orientation,
   2211                     dryrun=True,
-> 2212                     **kwargs)
   2213                 renderer = self.figure._cachedRenderer
   2214                 bbox_inches = self.figure.get_tightbbox(renderer)

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in print_png(self, filename_or_obj, *args, **kwargs)
    515 
    516     def print_png(self, filename_or_obj, *args, **kwargs):
--> 517         FigureCanvasAgg.draw(self)
    518         renderer = self.get_renderer()
    519         original_dpi = renderer.dpi

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in draw(self)
    435             # if toolbar:
    436             #     toolbar.set_cursor(cursors.WAIT)
--> 437             self.figure.draw(self.renderer)
    438             # A GUI class may be need to update a window using this draw, so
    439             # don't forget to call the superclass.

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/figure.pyc in draw(self, renderer)
   1491 
   1492             mimage._draw_list_compositing_images(
-> 1493                 renderer, self, artists, self.suppressComposite)
   1494 
   1495             renderer.close_group('figure')

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/image.pyc in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    139     if not_composite or not has_images:
    140         for a in artists:
--> 141             a.draw(renderer)
    142     else:
    143         # Composite any adjacent images together

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/axes/_base.pyc in draw(self, renderer, inframe)
   2633             renderer.stop_rasterizing()
   2634 
-> 2635         mimage._draw_list_compositing_images(renderer, self, artists)
   2636 
   2637         renderer.close_group('axes')

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/image.pyc in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    139     if not_composite or not has_images:
    140         for a in artists:
--> 141             a.draw(renderer)
    142     else:
    143         # Composite any adjacent images together

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/image.pyc in draw(self, renderer, *args, **kwargs)
    592         else:
    593             im, l, b, trans = self.make_image(
--> 594                 renderer, renderer.get_image_magnification())
    595             if im is not None:
    596                 renderer.draw_image(gc, l, b, im)

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/image.pyc in make_image(self, renderer, magnification, unsampled)
    840         return self._make_image(
    841             self._A, bbox, transformed_bbox, self.axes.bbox, magnification,
--> 842             unsampled=unsampled)
    843 
    844     def _check_unsampled_image(self, renderer):

/xxx/anaconda2/lib/python2.7/site-packages/matplotlib/image.pyc in _make_image(self, A, in_bbox, out_bbox, clip_bbox, magnification, unsampled, round_to_pixel_border)
    520                 alpha_channel = output[:, :, 3]
    521                 alpha_channel[:] = np.asarray(
--> 522                     np.asarray(alpha_channel, np.float32) * out_alpha * alpha,
    523                     np.uint8)
    524 

ValueError: operands could not be broadcast together with shapes (218,218) (100,100)

Expected outcome

Matplotlib version

  • Operating system:
  • Matplotlib version: 2.2.3
  • Matplotlib backend (print(matplotlib.get_backend())): TkAgg
  • Python version: 2.7.16
  • Jupyter notebook version (if applicable): 5.7.8
  • Other libraries: Numpy version: 1.16.5
@ImportanceOfBeingErnest
Copy link
Member

It doesn't look like the number 218 occurs anywhere in that linked script. Would you mind sticking to the template, providing the code that is run and the full error traceback, also filling out the version information (in this case the numpy version might be necessary as well)?

@ImportanceOfBeingErnest ImportanceOfBeingErnest added the status: needs clarification Issues that need more information to resolve. label Mar 11, 2020
@pink2289
Copy link
Author

That’s the issue. The number 218 indeed doesn’t occur anywhere in the script. I have updated the comment as per suggestion.

@ImportanceOfBeingErnest ImportanceOfBeingErnest removed the status: needs clarification Issues that need more information to resolve. label Mar 11, 2020
@ImportanceOfBeingErnest
Copy link
Member

Alright, if you are using matplotlib 2.2.3, it would make sense to refer to the corresponding example for that version.

https://matplotlib.org/2.2.3/gallery/images_contours_and_fields/image_transparency_blend.html

Can you confirm that this runs without error?

@ImportanceOfBeingErnest
Copy link
Member

So what's happening is that from matplotlib 3.2 on, alpha can be a matrix. This was introduced in #14889. Unfortunately, it seems it didn't get a what's new entry. In that sense the new transparency option is a bit opaque. Sorry for that.
I'm not sure if it's worth adding such entry retrospectively.

@pink2289
Copy link
Author

Ah! okay. Its running perfect. Thanks!

@QuLogic QuLogic added the Community support Users in need of help. label Jun 16, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Community support Users in need of help.
Projects
None yet
Development

No branches or pull requests

3 participants