python - Transform numpy array to RGB image array -


consider following code:

import numpy np rand_matrix = np.random.rand(10,10) 

which generates 10x10 random matrix.

following code display colour map:

import matplotlib.pyplot plt plt.imshow(rand_matrix) plt.show() 

i rgb numpy array (no axis) object obtained plt.imshow

in other words, if save image generated plt.show, 3d rgb numpy array obtained from:

import matplotlib.image mpimg img=mpimg.imread('rand_matrix.png') 

but without need save , load image, computationally expensive.

thank you.

you can save time saving io.bytesio instead of file:

import io import numpy np import matplotlib.pyplot plt import matplotlib.image mpimg pil import image  def ax_to_array(ax, **kwargs):     fig = ax.figure     frameon = ax.get_frame_on()     ax.set_frame_on(false)     io.bytesio() memf:         extent = ax.get_window_extent()         extent = extent.transformed(fig.dpi_scale_trans.inverted())         plt.axis('off')         fig.savefig(memf, format='png', bbox_inches=extent, **kwargs)         memf.seek(0)         arr = mpimg.imread(memf)[::-1,...]     ax.set_frame_on(frameon)      return arr.copy()  rand_matrix = np.random.rand(10,10) fig, ax = plt.subplots() ax.imshow(rand_matrix) result = ax_to_array(ax) # view using matplotlib plt.show() # view using pil result = (result * 255).astype('uint8') img = image.fromarray(result) img.show() 

enter image description here


Comments