I wrote a function with this purpose:
- to create a matplotlibfigure, but not display it
- with no frames, axes, etc.
- to plot in the figure an input 2D array using a user-passed colormap
- to save the colormapped 2D array from the canvas to a numpyarray
- that the output array should be the same size as the input
There are lots of questions with answers for tasks similar to either points 1-2 or point 4; for me it was also important to automate point 5. So I started by combining parts from both @joe-kington 's answer and from @matehat 's answer and comments to it, and with small modifications I got to this:
def mk_cmapped_data(data, mpl_cmap_name):
    
    # This is to define figure & ouptput dimensions from input
    r, c = data.shape
    dpi = 72
    w = round(c/dpi, 2)
    h = round(r/dpi, 2)    
    
    # This part modified from @matehat's SO answer: 
    # https://stackoverflow.com/a/8218887/1034648
    fig = plt.figure(frameon=False)
    fig.set_size_inches((w, h)) 
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    fig.add_axes(ax)
    plt.set_cmap(mpl_cmap_name)
    ax.imshow(data, aspect='auto', cmap = mpl_cmap_name, interpolation = 'none')
    fig.canvas.draw()    
    
    # This part is to save the canvas to numpy array
    # Adapted rom Joe Kington's SO answer: 
    # https://stackoverflow.com/a/7821917/1034648
    mat = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
    mat = mat.reshape(fig.canvas.get_width_height()[::-1] + (3,))
    mat = normalise(mat) # this is just using a helper function to normalize output range
    plt.close(fig=None)
    return mat
The function does what it is supposed to do and is fast enough. My question is whether I can make it more efficient and or more pythonic in any way.
 
    
 
    