matplotlib绘制显示图像时循环缓慢 [英] matplotlib draw is slow in loop when it showing an image

查看:114
本文介绍了matplotlib绘制显示图像时循环缓慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做的是在无限循环中交替显示 2 个图像到一个图形,直到用户单击窗口将其关闭.

What I'm doing is to show 2 images interchangeably to one figure in an infinite loop until the user clicks on the window to close it.

#import things
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import cv2
import time

#turn on interactive mode for pyplot
plt.ion()

quit_frame = False

#load the first image
img = cv2.imread("C:\Users\al\Desktop\Image1.jpg")
#make the second image from the first one
imggray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

def onclick(event):
    global quit_frame
    quit_frame = not quit_frame

fig = plt.figure()
ax = plt.gca()
fig.canvas.mpl_connect('button_press_event', onclick)

i = 0

while quit_frame is False:
    if i % 2 == 0: #if i is even, show the first image
        ax.imshow(img)
    else: #otherwise, show the second
        ax.imshow(imggray)

    #show the time for drawing
    start = time.time()
    plt.draw()
    print time.time() - start

    i = i + 1
    fig.canvas.get_tk_widget().update()
    if quit_frame is True:
        plt.close(fig)

这里的问题是,开始循环时打印的时间很小,但是逐渐增加:

The problem here is that the time printed is quite small at the begining loops but gradually increasing:

0.107000112534
0.074000120163
0.0789999961853
0.0989999771118
0.0880000591278
...
0.415999889374
0.444999933243
0.442000150681
0.468999862671
0.467000007629
0.496999979019
(and continue to increase)

我的期望是所有循环时间的绘制时间必须相同.我在这里做错了什么?

My expectation is the drawing time must be the same for all loop times. What I've done wrong here?

推荐答案

问题在于,每次调用 ax.imshow 时,都会向情节中添加一个额外的艺术家(即,您添加一个图像,而不是仅仅替换它).因此,在每次迭代中 plt.draw() 都有一个额外的图像要绘制.

The problem is that each time you call ax.imshow you add an additional artist to the plot (i.e., you add an image, instead of just replacing it). Thus, in each iteration plt.draw() has an additional image to draw.

要解决此问题,只需实例化艺术家一次(循环之前):

To solve this, just instantiate the artist once (before looping):

img_artist = ax.imshow(imggray)

然后在循环中,只需调用

And then in the loop, just call

img_artist.set_data(gray)

替换图像内容(或者当然是 img_artist.set_data(imggray))

to replace the image content (or img_artist.set_data(imggray) of course)

这篇关于matplotlib绘制显示图像时循环缓慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆