在matplotlib中缓慢的Line2D渲染

时间:2011-12-30 04:14:59

标签: python image matplotlib rendering

我正在尝试使用Line2D在点击多边形的最后一个点和用户的鼠标之间渲染一条线。我目前的代码目前有效,但它在渲染之间滞后,因此该行落后于鼠标。目前的相关代码是:

#in constructor 
cid2 = self.ui.canvas2.mpl_connect('motion_notify_event', self.renderMeasureLine)

#This gets called and is laggy
def renderMeasureLine(self, mouseEvent):            
    if self.measuring and mouseEvent.inaxes == self.ui.canvas2.axes and len(self.pointListX) > 0:

        if self.dotted_line in self.ui.canvas2.axes.lines:
            self.ui.canvas2.axes.lines.remove(self.dotted_line)
        self.dotted_line = Line2D([self.pointListX[-1],mouseEvent.xdata],[self.pointListY[-1],mouseEvent.ydata],
                                   color=color, axes=self.ui.canvas2.axes, ls = '--')
        self.ui.canvas2.axes.add_line(self.dotted_line)
        self.ui.canvas2.draw()

=============================================== =================================

#mpl canvas class
class MyDynamicMplCanvas(MyMplCanvas):
    """A canvas that updates itself every second with a new plot."""
    def __init__(self, *args, **kwargs):
        MyMplCanvas.__init__(self, *args, **kwargs)
        self.colorMap = cmap.bone

    def compute_initial_figure(self):
        self.axes.imshow(self.data, cmap = cmap.bone)

    def update_figure(self, dataOverride = None):
        if self.data is not None or dataOverride is not none:
            FigureCanvas.updateGeometry(self)
            self.axes.clear()
            if dataOverride is not None:
                self.axes.imshow(dataOverride, cmap = self.getColorMap())
            else:
                self.axes.imshow(self.data, cmap = self.getColorMap())
        self.draw()

基本上,每次鼠标移动时,我都要更新最后点击的多边形点和当前新鼠标位置之间的虚线。这是有效的,但它是超级延迟。任何想法??

编辑:正在发生的事情的图片。虚线是慢的。

enter image description here

1 个答案:

答案 0 :(得分:2)

不要为每次鼠标移动创建新的Line2DLine2D可以有超过2分。因此,请使用Line2D.set_data()更改单个Line2D中的数据。

用数千个点绘制一个Line2D肯定比实例化和绘制数千个Line2D更快。

def renderMeasureLine(self, mouseEvent):            
    if (self.measuring and mouseEvent.inaxes == self.ui.canvas2.axes
            and len(self.pointListX) > 0):
        if self.dotted_line in self.ui.canvas2.axes.lines:
            x, y = self.dotted_line.get_data()
            x.append(mouseEvent.xdata)
            y.append(mouseEvent.ydata)
            self.dotted_line.set_data(x, y)
        else:
            self.dotted_line = Line2D(
                [self.pointListX[-1],mouseEvent.xdata],
                [self.pointListY[-1],mouseEvent.ydata],
                color=color, axes=self.ui.canvas2.axes, ls = '--')
            self.ui.canvas2.axes.add_line(self.dotted_line)

        self.ui.canvas2.blit(self.ui.canvas2.axes.bbox)
        self.ui.canvas2.draw_idle()