hazrmard hazrmard - 4 months ago 30
Python Question

matplotlib - How to save an array as image with overlayed text?

I have a 2D array that I need to save as a

png
. I also need to add a text label to the image. So far, I have tried two approaches, none of which is optimal:


  • I use the
    matplotlib.image
    module to save the array directly as an image:

    matplotlib.image.imsave(FILENAME, ARRAY, cmap=plt.cm.binary)


    However I am unable to add text using that command. I could use
    PIL
    to read and edit after saving the raw images, but the I/O cost on a large data set would be unacceptable.

  • I use the
    pyplot
    interface to convert the array to a figure and then add a legend. However when I save it as a file, there is unnecessary whitespace. I have tried turning axes off, setting padding to 0 etc., but there is always some whitespace margin I cannot get rid of:

    import matplotlib.pyplot as plt
    plt.imshow(ARRAY, cmap=plt.cm.binary)
    plt.axis('off')
    plt.savefig(FILENAME, dpi=100, pad_inches=0.0, bbox_inches='tight')



Is there a way to generate an image from a 2D array, overlay text, and save as .png speedily with no whitespace? Preferably a solution using matplotlib/PIL, but if there's anything better out there, I can look into it.

Answer

I was able to solve my problem by using an object oriented approach from the start:

import matplotlib.pyplot as plt
fig = plt.figure(dpi=100, tight_layout=True, frameon=False, figsize=(resolution/100.,resolution/100.)) # dpi & figsize of my choosing
fig.figimage(ARRAY, cmap=plt.cm.binary)
fig.text(X,Y,TEXT, size='medium', backgroundcolor='white', alpha=0.5)
plt.savefig(FILENAME)
plt.close(fig)

Additional documentation for the figure class can be found here.

Note: For sizing figures, I found this relationship useful:
size in inches = resolution in pixels / DPI

Comments