Skip to content

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

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

Open
Song-Pingfan opened this issue Feb 18, 2025 · 1 comment

Comments

@Song-Pingfan
Copy link

Issue:

The following line in function show_factorization_on_image(img, explanations, colors = None, image_weight=0.5, concept_labels = None) gives AttributeError: 'FigureCanvasAgg' object has no attribute 'tostring_rgb'

data = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)

————————————————————————————
AttributeError Traceback (most recent call last)
in <cell line: 0>()
----> 1 visualization = show_factorization_on_image(rgb_img_float,
2 batch_explanations[0],
3 image_weight=0.3,
4 concept_labels=concept_label_strings)
5 result = np.hstack((img, visualization))

in show_factorization_on_image(img, explanations, colors, image_weight, concept_labels)
79 plt.axis('off')
80 fig.canvas.draw()
---> 81 data = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
82 # data = np.asarray(fig.canvas.buffer_rgba()) # data has shape (H, W, 4) (RGBA)
83 data = data[..., :3] # keep only RGB channels

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

Solution:

Try to use the canvas’s buffer to extract the image data.

Replace data = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8) by:

data = np.asarray(fig.canvas.buffer_rgba()) # data has shape (H, W, 4) (RGBA)
data = data[..., :3] # keep only RGB channels

Then, it works without any error.

@jacobgil
Copy link
Owner

Thank you! This was caused by maplotlib changes.
A PR will be greatly appreciated, otherwise I can test and add this in a few days.

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

No branches or pull requests

2 participants