Skip to content

Fix matplotlib >= 3.8 AttributeError in show_factorization_on_image#577

Open
Pchambet wants to merge 1 commit intojacobgil:masterfrom
Pchambet:fix/matplotlib-tostring-rgb-deprecation
Open

Fix matplotlib >= 3.8 AttributeError in show_factorization_on_image#577
Pchambet wants to merge 1 commit intojacobgil:masterfrom
Pchambet:fix/matplotlib-tostring-rgb-deprecation

Conversation

@Pchambet
Copy link

Problem

show_factorization_on_image raises an AttributeError with matplotlib >= 3.8:

AttributeError: 'FigureCanvasAgg' object has no attribute 'tostring_rgb'

FigureCanvasAgg.tostring_rgb() was deprecated in matplotlib 3.8 and removed in 3.10.

Fix

Replace tostring_rgb() with buffer_rgba(), which is the recommended successor:

# Before
data = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
plt.close(fig=fig)
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))

# After
data = np.asarray(fig.canvas.buffer_rgba())[..., :3].copy()
plt.close(fig=fig)

Why this works

tostring_rgb() (old) buffer_rgba() (new)
Return type flat bytes shaped memoryview (H × W × 4)
Channels RGB (3) RGBA (4)
Reshape needed yes (frombuffer + reshape) no (already H × W × 4)

Since buffer_rgba() returns a properly shaped RGBA array, we:

  1. Slice off the alpha channel with [..., :3] to get RGB
  2. Call .copy() to detach from the canvas buffer before plt.close() frees it
  3. Drop the now-unnecessary reshape call

Backward compatibility

buffer_rgba() has been available since matplotlib 3.1, so this change is backward-compatible with any matplotlib version that this library reasonably supports.

Fixes #556

Replace deprecated `FigureCanvasAgg.tostring_rgb()` with
`FigureCanvasAgg.buffer_rgba()`.

`tostring_rgb()` was deprecated in matplotlib 3.8 and removed in 3.10,
causing an `AttributeError` when calling `show_factorization_on_image`.

The new `buffer_rgba()` returns a shaped RGBA array directly, so the
manual `reshape` call is no longer needed. The alpha channel is sliced
off with `[..., :3]`, and `.copy()` ensures the data is independent of
the canvas buffer before the figure is closed.

Fixes jacobgil#556
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AttributeError: 'FigureCanvasAgg' object has no attribute 'tostring_rgb'

1 participant