0

I need to output a plot generated by Matplotlib as a grayscale np array with one channel. There are multiple answers like this one that generates output as RGB, but I can't find a method similar to tostring_rgb to call on the canvas and get it as a grayscale single-channel array.

1 Answer 1

1

You can use buffer_rgba to get the underlying buffer and then convert it to grayscale with your favorite formula, e.g. from here:

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

mpl.use('agg')
plt.bar([0,1,2], [1,2,3], color=list('cmy'))
canvas = plt.gcf().canvas
canvas.draw()

img = np.array(canvas.buffer_rgba())
img = np.rint(img[...,:3] @ [0.2126, 0.7152, 0.0722]).astype(np.uint8)

Result of mpl.use('qt5agg'), plt.imshow(img,'gray', vmin=0, vmax=255): enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.