我可以用文本覆盖做类似 imsave() 的事情吗?

Can I do something like imsave() with text overlay?

我正在按顺序使用 imsave() 来制作许多我将合并为 AVI 的 PNG,我想添加移动文本注释。我使用 ImageJ 制作 AVI 或 GIF。

我不需要坐标轴、数字、边框或任何东西,只需要彩色图像(如 imsave() 提供的示例),里面有文本(可能还有箭头)。这些将逐帧改变。请原谅使用jet。

我可以使用 savefig() 关闭勾号,然后像 post 处理一样进行裁剪,但是有没有更方便、直接或 "matplotlibithic" 的方法来做到这一点对我的硬盘驱动器来说不是那么难吗? (最后的东西会很大)

代码片段,应要求添加:

import numpy as np
import matplotlib.pyplot as plt

nx, ny = 101, 101

phi   = np.zeros((ny, nx), dtype = 'float')
do_me = np.ones_like(phi, dtype='bool')

x0, y0, r0 = 40, 65, 12

x = np.arange(nx, dtype = 'float')[None,:]
y = np.arange(ny, dtype = 'float')[:,None]
rsq = (x-x0)**2 + (y-y0)**2

circle = rsq <= r0**2

phi[circle] = 1.0
do_me[circle] = False

do_me[0,:], do_me[-1,:], do_me[:,0], do_me[:,-1] = False, False, False, False

n, nper = 100, 100
phi_hold = np.zeros((n+1, ny, nx))
phi_hold[0] = phi

for i in range(n):

    for j in range(nper):
        phi2 = 0.25*(np.roll(phi,  1, axis=0) +
                     np.roll(phi, -1, axis=0) +
                     np.roll(phi,  1, axis=1) +
                     np.roll(phi, -1, axis=1) )

        phi[do_me] = phi2[do_me]

    phi_hold[i+1] = phi

change = phi_hold[1:] - phi_hold[:-1]

places = [(32, 20), (54,25), (11,32), (3, 12)]

plt.figure()
plt.imshow(change[50])
for (x, y) in places:
    plt.text(x, y, "WOW", fontsize=16)
plt.text(5, 95, "Don't use Jet!", color="white", fontsize=20)
plt.show()

方法一

使用an excellent answer to another question as a reference, I came up with the following simplified variant which seems to work nicely - just make sure the figsize (which is given in inches)纵横比匹配绘图数据的大小比:

import numpy as np
import matplotlib.pyplot as plt

test_image = np.eye(100)
fig = plt.figure(figsize=(4,4))
ax = plt.axes(frameon=False, xticks=[],yticks=[])
ax.imshow(test_image)
plt.savefig('test.png', bbox_inches='tight', pad_inches=0)

请注意,我将 imshowtest_image 一起使用,这可能与其他绘图函数的行为不同...如果您想做某事,请在评论中告诉我否则。

另请注意,图像将被(重新)采样,因此 figsize 会影响写入图像的分辨率。

一样,figsize 设置与输出图像的大小(或屏幕上的大小,就此而言)不匹配。要克服这个问题,请使用...

方法二

阅读 FAQ 条目 Move the edge of an axes to make room for tick labels,我找到了一种使 figsize 参数直接设置输出图像大小的方法,方法是将轴的刻度移出可见区域:

import numpy as np
import matplotlib.pyplot as plt

test_image = np.eye(100)
fig = plt.figure(figsize=(4,4))
ax = fig.add_axes([0,0,1,1])
ax.imshow(test_image)
plt.savefig('test.png')

请注意,savefig 有一个默认的 DPI 设置(在我的例子中是 100),它与 figsize 一起决定了所保存图像在 x 和 y 方向上的像素数。您可以使用 savefig.

dpi 关键字参数覆盖它

如果您想在屏幕上显示图像而不是保存图像(通过使用 plt.show() 而不是上面代码中的 plt.savefig 行),图形的大小取决于 (除了已经熟悉的 figsize 参数) figure 的 DPI 设置,它也有一个默认值(在我的系统上是 80)。可以通过将 dpi 关键字参数传递给 plt.figure() 调用来覆盖此值。