Skip to content

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

Open
@Song-Pingfan

Description

@Song-Pingfan

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions