【发布时间】:2020-07-14 16:25:07
【问题描述】:
我需要将 Matplotlib 生成的绘图输出为具有一个通道的灰度 np 数组。有多个答案,如this one 生成为 RGB 的输出,但我找不到类似于tostring_rgb 的方法来调用画布并将其作为灰度单通道数组获取。
【问题讨论】:
标签: python python-3.x matplotlib
我需要将 Matplotlib 生成的绘图输出为具有一个通道的灰度 np 数组。有多个答案,如this one 生成为 RGB 的输出,但我找不到类似于tostring_rgb 的方法来调用画布并将其作为灰度单通道数组获取。
【问题讨论】:
标签: python python-3.x matplotlib
您可以使用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) 的结果:
【讨论】: