【问题标题】:Convert Matplotlib Figure to greyscale and b&w numpy array将 Matplotlib Figure 转换为灰度和黑白 numpy 数组
【发布时间】:2021-06-01 04:43:52
【问题描述】:

我正在绘制一些时间序列,将进一步用作 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,))

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

【问题讨论】:

  • 类似this question?
  • 可能,但我找不到黑白或灰度转换步骤

标签: python numpy matplotlib plot


【解决方案1】:

感谢conversion to RGB arrayconversion to grayscale and/or b&w array 上以下帖子的回答,我已经设法用以下代码解决了这个问题:

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")

【讨论】:

    猜你喜欢
    • 2013-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 2012-06-15
    • 1970-01-01
    • 2011-02-15
    • 2014-06-02
    相关资源
    最近更新 更多