我需要将Matplotlib生成的图输出为具有一个通道的灰度np数组。有多个答案,比如生成RGB输出的this one,但我找不到一个类似于tostring_rgb的方法来调用画布并将其作为灰度单通道数组。
发布于 2020-07-16 04:47:29
您可以使用buffer_rgba获取底层缓冲区,然后使用您最喜欢的公式将其转换为灰度,例如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)mpl.use('qt5agg'),plt.imshow(img,'gray', vmin=0, vmax=255)的结果:

https://stackoverflow.com/questions/62899642
复制相似问题