在现有图像上插入matplotlib文本并保留dpi

时间:2019-05-10 07:42:55

标签: python image matplotlib

我想在300 dpi分辨率的PNG格式的现有图像上使用matplotlib灵活文本功能。 我必须保留大小和分辨率。

我尝试了什么:

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()

但是我遇到边界框问题和dpi丢失(左边是之前,右边是之后):

enter image description here

在结果中保留原始图像特征的好方法是什么? 是否有替代的(在图像级别?)倾斜的文本框? 感谢您的任何建议。

1 个答案:

答案 0 :(得分:1)

生成具有正确大小和占据整个图形的轴的图形:

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)