2015-10-27 226 views
1

我想用鼠标绘制图像上的点。 问题:出现图像,但是当我点击鼠标时,没有任何绘图(即使点击几次)。使用鼠标绘制Python中图像上的点,用Matplotlib

我的Python版本是Python 2.7,带有Anaconda和IPython控制台。 在运行脚本之前,在Ipython控制台中键入%pylab。

这里是我的代码:

import numpy as np 
from matplotlib import pyplot as plt 
#Some code here [. . .] 

fig, ax = plt.subplots(1) 
ax.imshow(img, interpolation = 'bicubic') 
'''preventing plot from rescaling image:''' 
ax.set_xlim([0.0, img.shape[1]]) 
ax.set_ylim([img.shape[0], 0.0]) 
ax.hold(True) 
ax.autoscale = False 
#ax.plot(100,100, 'ro') # This works 

class MouseMonitor: 
    flag = True 
    x = 0. 
    y = 0. 
    fig = None 
    axes = None 

    def __init__(self, fig, ax): 
     self.axes = ax 
     self.fig = fig 
    def __call__(self, event): 
     if self.flag: 
      print('({}, {})'.format(event.xdata, event.ydata)) 
      self.flag = False 
     else: 
      d = np.linalg.norm([event.xdata - self.x, event.ydata - self.y]) 
      print('({}, {})\n\n distance between points: {} m\n\n-------------------\n'.format(event.xdata, event.ydata, d)) 
      self.flag = True      
     self.x = event.xdata 
     self.y = event.ydata 
     self.axes.plot(self.y, self.x, 'ro', linewidth = 5) #This don't work 

mouse = MouseMonitor(fig, ax) 

cid = fig.canvas.mpl_connect('button_press_event', mouse) 
+1

您需要在回调中添加一个'self.axes.figure.canvas.draw_idle()'调用,直到画布重绘为止。 OO方法很懒,以避免不必要的重绘。 – tacaswell

+0

'self.fig.canvas.draw_idle()'也会工作,没有看到你被捕获了。 – tacaswell

+0

谢谢你这么多tcaswell。它工作正常。 – MikeTeX

回答

1

从tcaswell评论答案:

添加self.axes.figure.canvas.draw_idle()调用步入回调。