Tuesday, November 11, 2014

[Python] Plot a Gaussian and overlay with an image

    x,y = np.random.multivariate_normal(mean, cov, 9000000).T
    x = x + center_x
    y = y + center_y

    heatmap, xedges, yedges = np.histogram2d(x, y, bins=(640, 480), range=[[0, 640], [0, 480]])
    extent = [0, 640, 0, 480]

    # convert heatmap to image
    heatmap = heatmap / max(heatmap.flatten())
    print max(heatmap.flatten())
    heatmap_im = Image.fromarray(np.uint8(cm.jet(np.transpose(heatmap))*255))
 
    blend_im = Image.blend(im.convert("RGBA"), heatmap_im, 0.4)
    blend_im.save("blend.png", "PNG")

[Python] Conversion from matplotlib figure to PIL image

def fig2img ( fig ):
    """
    @brief Convert a Matplotlib figure to a PIL Image in RGBA format and return it
    @param fig a matplotlib figure
    @return a Python Imaging Library ( PIL ) image
    """
    # put the figure pixmap into a numpy array
    buf = fig2data ( fig )
    w, h, d = buf.shape
    return Image.fromstring( "RGBA", ( w ,h ), buf.tostring( ) )

def fig2data ( fig ):
    """
    @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
    @param fig a matplotlib figure
    @return a numpy 3D array of RGBA values
    """
    # draw the renderer
    fig.canvas.draw ( )

    # Get the RGBA buffer from the figure
    w,h = fig.canvas.get_width_height()
    buf = numpy.fromstring ( fig.canvas.tostring_argb(), dtype=numpy.uint8 )
    buf.shape = ( w, h,4 )

    # canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
    buf = numpy.roll ( buf, 3, axis = 2 )
    return buf

[Python] save a figure in matplotlib with figure border removed

def SaveFigureAsImage(fileName,fig=None,**kwargs):
    ''' Save a Matplotlib figure as an image without borders or frames.
       Args:
            fileName (str): String that ends in .png etc.

            fig (Matplotlib figure instance): figure you want to save as the image
        Keyword Args:
            orig_size (tuple): width, height of the original image used to maintain
            aspect ratio.
    '''
    fig_size = fig.get_size_inches()
    w,h = fig_size[0], fig_size[1]
    fig.patch.set_alpha(0)
    if kwargs.has_key('orig_size'): # Aspect ratio scaling if required
        w,h = kwargs['orig_size']
        w2,h2 = fig_size[0],fig_size[1]
        fig.set_size_inches([(w2/w)*w,(w2/w)*h])
        fig.set_dpi((w2/w)*fig.get_dpi())
    a=fig.gca()
    a.set_frame_on(False)
    a.set_xticks([]); a.set_yticks([])
    plt.axis('off')
    plt.xlim(0,w); plt.ylim(h,0)
    fig.savefig(fileName, transparent=True, bbox_inches='tight', \
                        pad_inches=0)