B. M.
B. M.

Reputation: 18668

Insert a matplotlib text on an existing image and preserve dpi

I would like to use matplotlib flexible text abilities on an existing image in PNG format with 300 dpi resolution. I must preserve size and resolution.

what I tried :

from pylab import *
background = imread('Invitation.png')
imshow(background)
text(500,100, "n° 00001", size=20, rotation=30,
             ha="right", va="top",
             bbox=dict(boxstyle="round",
                       ec=(1., 0.5, 0.5),
                       fc=(1., 0.8, 0.8),
                     )) 
axis(off)
savefig('Invitation00001.png',dpi=300)
close()

But I encounter bounding box problems and dpi loss (left is before, right is after):

enter image description here

What is the good way to keep the original image features in the result? Is there an alternative (at image level ?) for slanted text box ? Thanks for any advice.

Upvotes: 1

Views: 2792

Answers (1)

Koen G.
Koen G.

Reputation: 778

Generate a figure with correct size and axes that occupy the whole figure:

import matplotlib.pyplot as plt
im = plt.imread('Invitation.png')
f = plt.figure(figsize = (im.shape[1]/300, im.shape[0]/300) #figure with correct aspect ratio
ax = plt.axes((0,0,1,1)) #axes over whole figure
ax.imshow(im)
ax.text(...) #whatever text arguments
ax.axis('off')
f.savefig('Invitation00001.png',dpi=300)

Upvotes: 2

Related Questions