首页 > 解决方案 > 将 Matplotlib Figure 转换为灰度和黑白 numpy 数组

问题描述

我正在绘制一些时间序列,这些时间序列将进一步用作 CNN 的输入。我需要将绘图转换为灰度和黑白格式的 NumPy 数组。这是绘制时间序列的代码部分:

    data = np.array([88, 70, 88.67903235, 50, 20, 88.66447851, 70, 88.65119164, 60]) 
    time = np.array([1,2,3,4,5,6,7,8,9])

    f = plt.figure(figsize=(5,5), dpi = 100)

    ax = f.add_axes([0,0,1,1])        
    ax.set_ylim(time[0], time[len(time)-1])        
    ax.set_xlim(0, 150)

    # y axis should be inverted
    ax.set_ylim(ax.get_ylim()[::-1])    

    ax.plot(data, time, "black")

    ax.axis('off')

上面的代码产生了这个图像:

在此处输入图像描述

我需要将其转换为灰度和黑白格式的 numpy 数组。

更新

我通过添加以下几行将其他一些答案整合到了:

f.tight_layout(pad=0)
ax.margins(0)
f.canvas.draw()

image_from_plot = np.frombuffer(f.canvas.tostring_rgb(), dtype=np.uint8)
image_from_plot = image_from_plot.reshape(f.canvas.get_width_height()[::-1] + (3,))

不幸的是,它给了我一些不同的东西,在垂直边界上被挤压

在此处输入图像描述

标签: pythonnumpymatplotlibplot

解决方案


感谢以下关于转换为 RGB 数组转换为灰度和/或黑白数组的帖子的答案,我已经设法用以下代码解决了这个问题:

DPI = 300

# data sample
data = np.array([88, 70, 88.67903235, 50, 20, 88.66447851, 70, 88.65119164, 60]) 
time = np.array([1,2,3,4,5,6,7,8,9])

# plot the figure without axes and margins 
f = plt.figure(figsize=(3,3), dpi = DPI)
ax = f.add_axes([0,0,1,1])    # remove margins       
ax.set_ylim(time[0], time[len(time)-1])    # y limits
ax.set_xlim(0, 150) # x limits
ax.set_ylim(ax.get_ylim()[::-1])    # invert y-axis
ax.plot(data, time, "black")    # plot the line in black
ax.axis('off')    # turn off axes


import io
io_buf = io.BytesIO()
f.savefig(io_buf, format='raw', dpi=DPI)
io_buf.seek(0)
img_arr = np.reshape(np.frombuffer(io_buf.getvalue(), dtype=np.uint8),
                  newshape=(int(f.bbox.bounds[3]), int(f.bbox.bounds[2]), -1))


from PIL import Image
col = Image.fromarray(img_arr) # RGB image
gray = col.convert('L') # grayscale image
bw = gray.point(lambda x: 0 if x<128 else 255, '1') # b&wimage

# saving
path = "C:/Users/<id>/<folder>/"

bw.save(path+"result_bw.png")
gray.save(path+"result_gray.png")
col.save(path+"result_col.png")

推荐阅读