0

I am plotting some time series, which will be further used as an input into CNN. I need to convert the plot into NumPy array of greyscale and b&w formats. Here is the part of the code that plots the time series:

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

The code above produces this image:

enter image description here

I need to convert it into the numpy array of greyscale and b&w format.

UPDATE

I have integrated some of the other answers into the by adding the following lines:

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

Unfortunately, it gives me something different, with squeezed in vertical boundaries

enter image description here

akkab
  • 401
  • 1
  • 6
  • 19

1 Answers1

0

Thanks to the answers from the following posts on conversion to RGB array and conversion to grayscale and/or b&w array, I have managed to solve the problem with the following code:

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")
akkab
  • 401
  • 1
  • 6
  • 19