Reputation: 1381
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.
Upvotes: 0
Views: 1010
Reputation: 30609
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)
:
Upvotes: 1