How can I speed up the conversion between matplotlib plots to a numpy arrays? My program creates millions of plots, and for each plot I want to return its numpy array (I do not care about viewing nor saving the plots! I only care about the conversion to numpy arrrays).
I managed to make the conversion with the following code:
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
Unfortunately, since I use: fig = plt.figure(num=1)
at the beginning, and plt.clf()
at the end, the program shows the images one by one on the figure, which slows everything down (about 1 to 2 frames per second).
I'm searching for a faster solution for the conversion from matplotlib plots to numpy arrays.
Update
I made the aggbackend change, but no improvement, where am I wrong? I'm attaching my code:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import imageio
from Game import Init, Draw, Game_step
images = []
Init()
fig = plt.figure(num=1)
Draw()
fig.canvas.draw()
for stp in range(100):
action_button = np.random.randint(4)
observation = Game_step(action_button)
Draw()
fig.canvas.draw()
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
images.append(data)
imageio.mimsave("game.gif", images, duration=1 / 35)
when Init: initialize the game, Draw: plot the current game screenshot in matplotlib, Game_step: taking one action in the game environment The goal is to get the np array of each screen plot
(I used Imagio just for checking, but it redundant)