首页 > 解决方案 > 显示 GIF 并等待按键

问题描述

我正在尝试自动标记图像序列。我需要相对于某个数字对它们进行排序,这可以由人工操作员轻松找到。

我的想法是为每个序列显示一个 gif(在屏幕上弹出),让操作员按下一个数字键,然后将序列复制到正确的位置,然后弹出另一个 gif,等等。

现在,我设法显示 gif,并等待按下按钮,但我无法获得按下的确切键......

知道该怎么做吗?而且我希望能够在将 gif 放在前面而不是在终端中时按下键...

这是我的代码:

    fig = plt.figure()
    for img in sequence:
        im = plt.imshow(img_array,animated=True,cmap='gray')
        ims.append([im])

    ani = animation.ArtistAnimation(fig,ims,interval=50,blit=True,repeat_delay=1000)
    plt.draw()
    plt.pause(1)
    n = raw_input("how many?")
    plt.close(fig) ## shows all the gifs at once, opening multiple windows.

标签: pythonpython-3.xmatplotlib

解决方案


我不认为你想在这里使用动画,因为这只会给用户一个固定的、有限的时间来决定按下一个键。相反,使用按键来触发对下一个图像的更改。

import numpy as np
import matplotlib.pyplot as plt

images = [np.random.rand(10,10) for i in range(13)]

fig, ax = plt.subplots()

im = ax.imshow(images[0], vmin=0, vmax=1, cmap='gray')

curr = [0]
def next_image(evt=None):
    n = int(evt.key)
    # do something with current image
    print("You pressed {}".format(n))
    # advance to next image
    if curr[0] < len(images)-1:
        curr[0] += 1
        im.set_array(images[curr[0]])
        fig.canvas.draw_idle()
    else:
        plt.close()

fig.canvas.mpl_connect("key_press_event", next_image)        
plt.show()

推荐阅读