Mehdi Zare
Mehdi Zare

Reputation: 1381

Output Matplotlib plot as grayscale array

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

Answers (1)

Stef
Stef

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): enter image description here

Upvotes: 1

Related Questions